字符串是字符的顺序存储,也就是字符数组。这道题是先看了书上的思路之后做的,一开始用char*指针遍历出现报错。之后看了书上的具体实现,用数组索引的方式代替,顺利通过。
通过的代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
if(str==nullptr || length<=0){
return;
}
int newLen = length;
for(int i=0; i<length; i++){
if(str[i]==' '){
newLen += 2;
}
}
int p1 = length-1;
int p2 = newLen-1;
while(p1>=0 && p2>p1){
if(str[p1] == ' '){
str[p2--] = '0';
str[p2--] = '2';
str[p2--] = '%';
}
else{
str[p2--] = str[p1];
}
--p1;
}
}
};
附上第一次报错的代码:
class Solution {
public:
void replaceSpace(char *str,int length) {
char* temp = str;
int newlen = length;
for(int i=0; i<length; i++){
if(*temp == ' '){
newlen += 2;
}
temp++;
}
temp--;
char* p1=temp, p2=str+newlen-1;
for(int i=0; i<length; i++){
if(*p1 == ' '){
*(p2--) = '0';
*(p2--) = '2';
*(p2--) = '%';
}
else{
*p2 = *p1;
}
if(p1 != str) p1--;
}
}
};
1、第一次报错,语法错误:
报错信息:cannot initialize a variable of type 'char' with an rvalue of type 'char *'
错在了这一行:char* p1=temp, p2=str+newlen-1;
将char* p1=temp, p2=str+newlen-1; 这一行进行修改。
改成 char* p1 = temp; char* p2 = str+newlen-1; 或者char* p1=temp, *p2=str+newlen-1;
编译即可通过,但是测试用例全部通不过,结果显示输出空格没变。
2、第二次报错,程序逻辑有误:
else里面的*p2 = *p1; 赋值之后没有让p2指针左移一位,因为这里遗漏了p2--,导致结果不对;
for(int i=0; i<length; i++){
if(*p1 == ' '){
*(p2--) = '0';
*(p2--) = '2';
*(p2--) = '%';
}
else{
*p2-- = *p1;
}
if(p1 != str) p1--;
}