This is a question from careercup.com. You are given an alphanumeric string. Complete the function sortSegments that will segment the string into substrings of consecutive letters or numbers and then sort the substrings. For example, the string "AZQF013452BAB" will result in "AFQZ012345ABB". The input letters will be uppercase and numbers will be between 0 and 9 inclusive.
#include <iostream>
#include <string>
#include <algorithm>
void sortSegments(std::string& input)
{
bool toggle1 = isalpha(input[0])? true: false;
size_t k = 0;
for(size_t i = 1; i <= input.size(); ++i)
{
bool toggle2 = isalpha(input[i])? true: false;
if(toggle1 != toggle2)
{
std::sort(input.begin()+k, input.begin()+i);
toggle1 = toggle2;
k=i;
}
}
}
int main()
{
std::string input("AZQKF013452BAB");
sortSegments(input);
std::cout << input;
}
1 Answer 1
FWIW, your function has a bug.
If you change the input string to "AZQKF013452BAB98"
, you will notice the problem.
The reason for the bug it that the null character is neither a digit nor an alphabetical character.
Here's an updated version of the function that fixes the bug.
void sortSegments(std::string& input)
{
bool toggle1 = isalpha(input[0])? true: false;
size_t k = 0;
// Change the <= to <
for(size_t i = 0; i < input.size(); ++i)
{
bool toggle2 = isalpha(input[i])? true: false;
if(toggle1 != toggle2)
{
std::sort(input.begin()+k, input.begin()+i);
toggle1 = toggle2;
k=i;
}
}
// Sort the remaining characters.
std::sort(input.begin()+k, input.end());
}
-
1\$\begingroup\$ Why do you need i outside the loop? it should be equal to
input.size()
when loop exits, or just pass input.end(). I would rewrite it using iterators from the beginning \$\endgroup\$Artemy Vysotsky– Artemy Vysotsky2017年09月12日 04:04:59 +00:00Commented Sep 12, 2017 at 4:04 -
\$\begingroup\$ @ArtemyVysotsky, good point. \$\endgroup\$R Sahu– R Sahu2017年09月12日 05:08:40 +00:00Commented Sep 12, 2017 at 5:08
-
1\$\begingroup\$ your fix is not good - choose begin()+size() or end(). Just size() will not compile \$\endgroup\$Artemy Vysotsky– Artemy Vysotsky2017年09月12日 05:13:27 +00:00Commented Sep 12, 2017 at 5:13
Explore related questions
See similar questions with these tags.
std::cout << sortSegments(input) << '\n';
\$\endgroup\$