替换空格

题目链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
题目描述:

题解:
空间复杂度:O(1)
1.先找出字符串中含有多少个空格
2.对原字符串空间扩容
3.定义两个指针,一个指向新字符串的末尾,一个指向原始字符串的末尾

class Solution {
public:
    string replaceSpace(string s) {
        int count = 0;
        int sOldSize = s.size();
        for(auto iter: s)
        {
            if(iter == ' ')
                count++;
        }
        s.resize(s.size() + count * 2);
        int sNewSize = s.size();
        for(int i = sNewSize - 1, j = sOldSize - 1; j < i; i--, j--)
        {
            if(s[j] != ' ')
            {
                s[i] = s[j];
            }else{
                s[i] = '0';
                s[i - 1] = '2';
                s[i - 2] = '%';
                i -= 2;
            }
        }
        return s;

    }
};

空间复杂度:O(N)


class Solution {
public:
    string replaceSpace(string s) {     //字符数组
        string array;   //存储结果
        
        for(auto &c : s){   //遍历原字符串
            if(c == ' '){
                array += "%20";
            }
            else{
                array += c;
            }
        }
        return array;
    }
};

posted @ 2021-06-16 14:48  张宵  阅读(32)  评论(0编辑  收藏  举报