题目地址: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;
}









网友评论