鉴于字母数字字符的字符串str,任务是单独排序的连续字符类似的团体和打印修改后的字符串即数字和字母字符的所有连续组将分别进行排序。
例子:
Input: str = “121geeks21”
Output: 112eegks12
“121”, “geeks”, “21” are the valid groups
and they will be sorted separately.
Input: str = “cba321ab”
Output: abc123ab
方法:创建一个向量来存储给定字符串中所有有效组的起始索引。现在,由字符遍历字符串字符,如果当前字符是从不同的组比以前的字符然后按当前索引到载体中。后字符串已遍历完全,排序的所有使用前面更新了矢量给定字符串的子串的各个组。最后,打印修改后的字符串。
下面是上述方法的实现:
// C++ implementation of the approach
#include
using namespace std;
// Function to return the modified string
string get_string(string str, int n)
{
// To store the previous character
char prev = str[0];
// To store the starting indices
// of all the groups
vector result;
// Starting index of the first group
result.push_back(0);
for (int i = 1; i < n; i++) {
// If the current character and the
// previous character differ
if (isdigit(str[i]) != isdigit(prev)) {
// Push the starting index
// of the new group
result.push_back(i);
}
// The current character now becomes previous
prev = str[i];
}
// Sort the first group
sort(str.begin(), str.begin() + result[0]);
// Sort all the remaining groups
for (int i = 0; i < result.size() - 1; i++) {
sort(str.begin() + result[i],
str.begin() + result[i + 1]);
}
// Sort the last group
sort(str.begin() + result[result.size() - 1],
str.end());
// Return the modified string
return str;
}
// Driver code
int main()
{
string str = "121geeks21";
int n = str.length();
cout << get_string(str, n);
return 0;
}
输出:
112eegks12