题目描述
知识点
字符串string STL操作
结果
实现
码前思考
- 本来是想暴力求解的,但是记得C++ STL里面有现成的函数,所以还是决定用现成的函数来解题;
代码实现
class Solution {
public:
string replaceSpace(string s) {
int pos = 0;
int srclen = 1;
int dstlen = 3;
while( (pos=s.find(" ",pos)) != string::npos){
s.replace(pos,srclen,"%20");
pos += dstlen;
}
return s;
}
};
码后反思
-
这里用到了两个函数
.find()
和.replace()
,这两个函数是我在以前的笔记里面看到的,现在已经忘了👉C++STL之string -
-
-
但是需要注意时间复杂度,
.find()
的时间复杂度为 O ( n m ) O(nm) O(nm),每次循环都用这个,感觉时间复杂度有一点点高。 -
网络上的纯手写解答
需要注意的是这里(j-i)/2
代表还有多少个空格没有被处理到,所以当i==j
时,说明已经处理完所有的空格了,因此可以提前返回。class Solution { public: string replaceSpace(string s) { int count = 0,len = s.size(); //统计空格数量 for(char c : s){ if(c == ' '){ count++; } } //修改s长度 s.resize(len+2*count); //倒序遍历 int i=len-1; int j=len+2*count-1; while(i!=j){ if(s[i] != ' '){ s[j] = s[i]; i--; j--; }else{ s[j]='0'; s[j-1]='2'; s[j-2]='%'; i--; j=j-3; } } return s; } };