替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
限制:
0 <= s 的长度 <= 10000
1. C++
解题思路:
1.利用c++11 以后遍历容器的方法 for(auto a:s) ,res 为新建的string
class Solution {
public:
string replaceSpace(string s) {
string res;
for(auto a:s){
if(a == ' ') res += "%20";
else res += a;
}
return res;
}
};
2.一般像这种需要向后扩充容量重新整理内存的,最好能够考虑到从尾部开始整理的方法
1.指针都可以当作数组使用,但是指针本身不检查是否超出数组范围。
2.对字符串的处理都应该考虑最后的空字符’\0’。
3.应该一个一个的处理字符串中的字符,不要向一蹴而就。
4.扩充字符串可以考虑从尾部开始。
5.应该警惕内存覆盖,如果改变字符串会导致字符串变长,那应该考虑内存的问题
从尾部开始扩展倒置
#include <vector>
#include <iostream>
using namespace std;
void replaceSpace(char *str, int length) {
if (str == nullptr || length <= 0)return;
int spaceCnt = 0,orginalCnt = 0;
char *tmpStr = str;
while (*tmpStr != '\0') {
if (*tmpStr == ' ')
spaceCnt++;
tmpStr++;
orginalCnt++;
}
int end = orginalCnt + 2 * spaceCnt;
if (end+1 > length) {
return;
}
str[end--] = '\0';
for (int i = orginalCnt-1; i >= 0; i--) {
if (str[i] != ' ') {
str[end--] = str[i];
}
else {
str[end--] = '0';
str[end--] = '2';
str[end--] = '%';
}
}
}
来源:CSDN
作者:xiaohe004
链接:https://blog.csdn.net/xiaohe004/article/details/104673066