"Programmer Code Interview Guide" - Space Replacement in Strings (C++ Implementation)

Topic description:

Replacing spaces in the string with "%20" requires a time complexity of O(N) and a space complexity of O(1)

Ideas:

"Swordsman Offer" also has the same topic. The space complexity is O(1), which means that another array is not allowed to store new strings. The time complexity is O(N), which can be guaranteed by traversing from the end to the beginning. , the specific code is as follows:

C++ code implementation:

#include<iostream>

#include<string>

using namespacestd;

int main(){

    char str[1024];

    //Read in a line of string, gets used with char[] array

    gets(str);

    int len ​​= 0 ;

    int numOfBlank=0;

    // Calculate the number of spaces in the string and the length of the string

    for(int i=0;str[i]!='\0';i++){

        if(str[i]==' ')

            numOfBlank ++;

        len ++;

    }

    // print to check if the space calculation is correct

    cout<<numOfBlank<<endl;

    // length after replacing spaces

    int newLen = len + 2 * numOfBlank- 1 ;

    //Replace spaces from the end to the beginning, panning the string

    for(int i=len-1;i>=0;i--){

        if(str[i]!=' ')

            str [newLen -] = str [i];

        else{

            str [newLen -] = '0' ;

            str [newLen -] = '2' ;

            str [newLen -] = '%' ;

        }

    }

    cout<<str<<endl;

    return0;

}

Program running result:

ss jj kk 

3

ss%20jj%20kk%20

Program ended with exit code: 0



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325933435&siteId=291194637