Given 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.
Examples:
Input: str = “121geeks21”
Output: 112eegks12
Explanation: “121”, “geeks”, “21” are the valid groups
and they will be sorted separately.Input: str = “cba321ab”
Output: abc123ab
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 a substring of the given string using the vector updated earlier. Finally, print the modified string.
Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> 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< int > 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]);
}
//cout<<str<<endl;
// 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;
} |
# Python 3 implementation of the approach # Function to return the modified string def get_string(st, n):
# To store the previous character
prev = st[ 0 ]
# To store the starting indices
# of all the groups
result = []
# Starting index of the first group
result.append( 0 )
for i in range ( 1 , n):
# If the current character and the
# previous character differ
if (st[i].isdigit() ! = prev.isdigit()):
# Push the starting index
# of the new group
result.append(i)
# The current character now becomes previous
prev = st[i]
# Sort the first group
st = list (st)
st[:result[ 0 ]].sort()
p = st.copy()
# Sort all the remaining groups
for i in range ( len (result) - 1 ):
p[result[i]:result[i + 1 ]] = sorted (st[result[i]:result[i + 1 ]])
# print(''.join(st))
# Sort the last group
p[ len (p) - 2 :] = sorted (st[result[ - 1 ]:])
# Return the modified string
return ''.join(p)
# Driver code if __name__ = = "__main__" :
st = "121geeks21"
n = len (st)
print (get_string(st, n))
# This code is contributed by ukasp.
|
import java.util.*;
public class Main {
// Function to return the modified string
static String get_string(String str, int n) {
// To store the previous character
char prev = str.charAt( 0 );
// To store the starting indices
// of all the groups
List<Integer> result = new ArrayList<>();
// Starting index of the first group
result.add( 0 );
for ( int i = 1 ; i < n; i++) {
// If the current character and the
// previous character differ
if (Character.isDigit(str.charAt(i)) != Character.isDigit(prev)) {
// Push the starting index
// of the new group
result.add(i);
}
// The current character now becomes previous
prev = str.charAt(i);
}
// Sort the first group
char [] charArray = str.toCharArray();
Arrays.sort(charArray, 0 , result.get( 0 ));
// Sort all the remaining groups
for ( int i = 0 ; i < result.size() - 1 ; i++) {
Arrays.sort(charArray, result.get(i), result.get(i + 1 ));
}
// Sort the last group
Arrays.sort(charArray, result.get(result.size() - 1 ), n);
// Return the modified string
return new String(charArray);
}
// Driver code
public static void main(String[] args) {
String str = "121geeks21" ;
int n = str.length();
System.out.println(get_string(str, n));
}
} // This code is contributed by Prince Kumar |
// C# program for the above approach using System;
using System.Collections.Generic;
public class Program {
// Function to return the modified string
static string GetModifiedString( string str, int n) {
// To store the previous character
char prev = str[0];
// To store the starting indices
// of all the groups
List< int > result = new List< int >();
// Starting index of the first group
result.Add(0);
for ( int i = 1; i < n; i++) {
// If the current character and the
// previous character differ
if ( char .IsDigit(str[i]) != char .IsDigit(prev)) {
// Push the starting index
// of the new group
result.Add(i);
}
// The current character now becomes previous
prev = str[i];
}
// Sort the first group
char [] charArray = str.ToCharArray();
Array.Sort(charArray, 0, result[0]);
// Sort all the remaining groups
for ( int i = 0; i < result.Count - 1; i++) {
Array.Sort(charArray, result[i], result[i + 1] - result[i]);
}
// Sort the last group
Array.Sort(charArray, result[result.Count - 1], n - result[result.Count - 1]);
// Return the modified string
return new string (charArray);
}
// Driver code
public static void Main( string [] args) {
string str = "121geeks21" ;
int n = str.Length;
Console.WriteLine(GetModifiedString(str, n));
}
} // This code is contributed by rishabmalhdjio |
// JavaScript implementation of the approach function get_string(str, n)
{ // To store the previous character
let prev = str[0];
// To store the starting indices of all the groups
let result = [];
// Starting index of the first group
result.push(0);
for (let i = 1; i < n; i++) {
// If the current character and the previous character differ
if (isNaN(parseInt(str[i])) !== isNaN(parseInt(prev))) {
// Push the starting index of the new group
result.push(i);
}
// The current character now becomes previous
prev = str[i];
}
// Sort the first group
str = str.substr(0, result[0]) +
str.substr(result[0], result[1] - result[0])
.split( '' ).sort().join( '' ) +
str.substr(result[1]);
// Sort all the remaining groups
for (let i = 1; i < result.length - 1; i++) {
str = str.substr(0, result[i]) +
str.substr(result[i], result[i + 1] - result[i])
.split( '' ).sort().join( '' ) +
str.substr(result[i + 1]);
}
// Sort the last group
str = str.substr(0, result[result.length - 1]) +
str.substr(result[result.length - 1])
.split( '' ).sort().join( '' );
// Return the modified string
return str;
} // Driver code let str = "121geeks21" ;
let n = str.length; console.log(get_string(str, n)); |
112eegks12
Time complexity: O(n*nlogn)
Auxiliary Space: O(n)