Interview questions. URLification (replace spaces with characters)

URLify. Write a method that replaces all spaces in a string with %20. It is assumed that there is enough space at the end of the string to hold the new characters, and that the "true" length of the string is known. (Note: For Javaimplementation, please use character arrays to operate directly on the array.)

Example 1:

Input: "Mr John Smith ", 13
Output: "Mr%20John%20Smith"

Example 2:

Input: " ", 5
Output: "%20%20%20%20%20"

code show as below:

class Solution {
public:
    string replaceSpaces(string S, int length) {
        int count =0;
        for(int i=0;i<length;i++)
        {
            if(S[i]==' ')
            {
                count++;//记录空格的个数
            }
        }
        int newlen=length+count*2;//定义存放进字符后新的字符串的长度
        S.resize(newlen);//更新字符串的长度
        int i=length-1,j=newlen-1;
        while(i>=0)
        {
            if(S[i]!=' ')//如果没有遇到空格就将字符后移,移到正确的位置上
            {
                S[j]=S[i];
                j--;
                i--;
            }
            else
            {
                S[j]='0';//遇到空格将字符插进空格里
                S[j-1]='2';
                S[j-2]='%';
                j-=3;
                i--;
            }
        }
        return S;//返回原来的字符串
    }
};

Guess you like

Origin blog.csdn.net/m0_62379712/article/details/132232101