Sort groups of numbers and characters separately in a String
Given a string str of alphanumeric characters, the task is to sort the similar group of consecutive characters separately and print the modified string i.e. all consecutive groups of digits and alphabetical characters will be sorted separately.
Input: str = “121geeks21”
“121”, “geeks”, “21” are the valid groups
and they will be sorted separately.
Input: str = “cba321ab”
Approach: Create a vector to store the starting indices of all the valid groups in the given string. Now, traverse the string character by character and if the current character is from a different group than the previous character then push the current index to the vector. After the string has been traversed completely, sort all the individual groups of substring of the given string using the vector updated earlier. Finally, print the modified string.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.