双指针应用三:替换空格

题目地址:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/

题目描述: 请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
参考代码:

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

class Solution {
public: string replaceSpace(string s) {
    int count = 0;
    for (int i = 0; i < s.size(); i++) {
        if (s[i] == ' ') {
            count ++;
        }
    }
    int oldSize = s.size();
    s.resize(s.size() + count *2);
    int newIndex = s.size() -1 ;
    for (int i = oldSize - 1; i >= 0; i--) {
        if (s[i] == ' ') {
            //"%20"
            s[newIndex--] = '0';
            s[newIndex--] = '2';
            s[newIndex--] = '%';
        } else {
            s[newIndex--] = s[i];
        }
    }
    return s;
    }
};

int main(int argc, const char * argv[]) {
    string str = "hello ";
    Solution().replaceSpace(str);
    return 0;
}

参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/%E5%89%91%E6%8C%87Offer05.%E6%9B%BF%E6%8D%A2%E7%A9%BA%E6%A0%BC.md

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容