自己费了九牛二虎之力,看过答案,过了很久后 写的代码:
1 class Solution { 2 public: 3 void replaceSpace(char *str,int length) { 4 int num0 = 0; 5 for(int i =0 ;i< length ;i++){ 6 if(str[i]== ' '){ 7 num0++; 8 } 9 } 10 int num = 2 * num0; //这里一开始忘了,导致溢出,后来又乘以3 更加不对了 11 int j = 0; 12 for (int i = 0 ;i<length ;i++){ 13 14 if(str[length -i -1] != ' '){ 15 str[length+num-1-j] = str[length -1-i]; 16 j++; 17 } 18 else{ 19 str[length +num -1-j] ='0'; 20 j++; 21 str[length +num -1-j] ='2'; 22 j++; 23 str[length +num -1-j] ='%'; 24 j++; 25 26 } 27 } 28 } 29 };
榜首答案:虽然思想一样,但是人家的特别干练,且变量的赋值很讲究。
1 class Solution { 2 public: 3 void replaceSpace(char *str,int length) { 4 if(str==NULL) 5 return ; 6 int CountOfBlanks=0; 7 int Originallength=0; 8 for(int i=0;str[i]!='