Monday, December 5, 2022
HomeSoftware DevelopmentHow you can insert characters in a string at a sure place?

How you can insert characters in a string at a sure place?


View Dialogue

Enhance Article

Save Article

Like Article

View Dialogue

Enhance Article

Save Article

Like Article

Given a string str and an array of indices chars[] that describes the indices within the unique string the place the characters will likely be added. For this put up, let the character to be inserted in star (*). Every star must be inserted earlier than the character on the given index. Return the modified string after the celebrities have been added.

Examples:

Enter: str = “geeksforgeeks”, chars = [1, 5, 7, 9]
Output: g*eeks*fo*rg*eeks
Clarification: The indices 1, 5, 7, and 9 correspond to the daring characters in “geeksforgeeks”.

Enter: str = “spacing”, chars = [0, 1, 2, 3, 4, 5, 6]
Output: “*s*p*a*c*i*n*g”

Strategy: To resolve the issue comply with the beneath concept:

Iterate over the string and preserve observe of the rely of the characters within the string to this point and each time your rely turns into equal to the component within the array of stars, append a star to the resultant string and transfer forward in your star array.

Observe the steps talked about beneath to implement the thought:

  • Create a string ans for storing your resultant string.
  • Take one pointer j initially as 0.
  • Iterate over the string and each time your index that represents the rely of characters turns into equal to the component in stars[j], append the star in your ans string and transfer the j pointer forward.
  • Additionally, at every transfer, append the present character in your string ans.

Beneath is the implementation of the above strategy:

C++

  

#embody <bits/stdc++.h>

utilizing namespace std;

  

string addStars(string s, vector<int>& stars)

{

  

    

    

    string ans = "";

  

    int j = 0;

  

    for (int i = 0; i < s.size(); i++) {

  

        

        

        

        if (j < stars.measurement() && i == stars[j]) {

            ans += '*';

            j++;

        }

        ans += s[i];

    }

  

    return ans;

}

  

int important()

{

    string str = "geeksforgeeks";

    vector<int> chars = { 1, 5, 7, 9 };

    string ans = addStars(str, chars);

  

    

    cout << ans << endl;

}

Time Complexity: O(N)
Auxiliary Area: O(N)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments