【算法】将字符串中的空格替换成指定字符串

题目:

字符串中的空格替换成指定字符串,如%20。

给定一个字符串,内部有空格,请用最少的时间复杂度、空间复杂度,将空格替换为%20

示例:

输入:
This is a test string
输出:
This%20is%20a%20test%20%string

思路:

只创建所需的额外空间

采用逆序双索引进行逐个移动,正序遍历移动量较大。


关键点:

逆序处理,利用原内存空间,双索引(或指针)


实现:

c++

#include <iostream>
#include <string>
using namespace std;

class Solution{
public:
    // str: 输入字符串
    // pad: 填充的字符串
    string replaceBlank(string str, string pad){
        int padLen = pad.length();
        int strLen = str.length();
        int blankSize = 0;
        //统计空格个数
        for(int i=0; i<strLen; i++){
            if(str[i]==' ')
                blankSize ++;
        }
        //统计所需新增内存
        int memNeed = (padLen-1) * blankSize;
        str += string(memNeed, ' ');
        int newIndex = str.length()-1;
        int oldIndex = strLen-1;
        //逆序循环
        while(oldIndex>=0){
            if(str[oldIndex]!=' '){
                str[newIndex--] = str[oldIndex--];
            }else{
                //替换符逆序填补
                for(int i=padLen-1; i>=0; i--){
                    str[newIndex--] = pad[i];
                }
                oldIndex --;
            }
        }
        return str;
   }
};

int main(){
    string str = "This is a test";
    string pad = "%20";
    Solution slu = Solution();
    string result = slu.replaceBlank(str, pad);
    cout << "input: " << str << endl;
    cout << "pad: " << pad << endl;
    cout << "output: " << result << endl;
}

猜你喜欢

转载自blog.csdn.net/JasonZhu_csdn/article/details/82889178