Thursday, March 4, 2021

Published March 04, 2021 by Anonymous with 0 comment

Sort a string without altering the position of vowels

Sort a string without altering the position of vowels

Given a string S of size N, the task is to sort the string without changing the position of vowels.

Examples:

Input: S = “geeksforgeeks”
Output: feeggkokreess
Explanation:
The consonants present in the string are gksfrgks. Sorting the consonants modifies their sequence to fggkkrss.
Now, update the string by placing the sorted consonants in those positions.

Input: S = “apple”
Output: alppe

Approach: Follow the steps below to solve the problem:

Below is the implementation of the above approach:

C++

#include <bits/stdc++.h>

using namespace std;

  

void sortStr(string S)

{

    

    int N = S.size();

  

    string temp = "";

  

    

    for (int i = 0; i < N; i++) {

        if (S[i] != 'a' && S[i] != 'e' && S[i] != 'i'

            && S[i] != 'o' && S[i] != 'u')

            temp += S[i];

    }

  

    

    if (temp.size())

        sort(temp.begin(), temp.end());

  

    

    

    int ptr = 0;

  

    

    for (int i = 0; i < N; i++) {

        if (S[i] != 'a' && S[i] != 'e' && S[i] != 'i'

            && S[i] != 'o' && S[i] != 'u')

            S[i] = temp[ptr++];

    }

  

    cout << S;

}

  

int main()

{

    string S = "geeksforgeeks";

    sortStr(S);

    return 0;

}

Output:
feeggkokreess

Time Complexity: O(N logN)
Auxiliary Space: O(N)

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.

Let's block ads! (Why?)

      edit

0 comments:

Post a Comment