题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路1:(不开辟新空间)
1 class Solution { 2 public: 3 void replaceSpace(char *str,int length) { 4 if (str== nullptr||length<=0) return; 5 int i=0,str_len=0,blank_count=0; 6 while (str[i]!='\0'){ 7 str_len++; 8 if (str[i]==' ') blank_count++; 9 i++; 10 } 11 int p=str_len+2*blank_count,q=str_len; 12 while (q>=0){ 13 if (str[q]==' '){ 14 str[p--]='0'; 15 str[p--]='2'; 16 str[p--]='%'; 17 } 18 else{ 19 str[p--]=str[q]; 20 } 21 q--; 22 } 23 } 24 };
思路:
时间复杂度O(n)
空间复杂度O(1)
计算出多少个空格,得到目标字符串的长度 (原字符串长度+空格数*2),然后从尾向头遍历即可。
思路2:(借用辅助数组)