Friday, October 7, 2022
HomeWordPress DevelopmentThe right way to insert characters in a string at a sure...

The right way to 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 can 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 celebs 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”

Method: To unravel the issue observe the under concept:

Iterate over the string and preserve monitor of the depend of the characters within the string to this point and every time your depend 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 under 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 every time your index that represents the depend 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 method:

C++

  

#embrace <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.dimension() && i == stars[j]) {

            ans += '*';

            j++;

        }

        ans += s[i];

    }

  

    return ans;

}

  

int major()

{

    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

- Advertisment -
Google search engine

Most Popular

Recent Comments