劍指offer替換空格:
請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之后的字符串為We%20Are%20Happy。
思路:當我們從前往后進行替換時,每替換一個就要移動后面的所有字符,時間復雜度是0(n2)
我們可以從后向前替換,先統計出所有的空格數space_count,就能得到替換后的長度是length+2*space_count
定義兩個指針(可以用下標表示),i指向替換前的最后一個字符下標,j指向替換后的最后一個字符下標
從后向前復制。
1 //請實現一個函數,將一個字符串中的每個空格替換成“%20”。 2 //例如,當字符串為We Are Happy. 3 //則經過替換之后的字符串為We%20Are%20Happy。 4 #include <iostream> 5 #include <cstring> 6 #include <cstdlib> 7 using namespace std; 8 9 10 class Solution { 11 public: 12 //思路首先找出統計所有的空格數,這樣就能計算出替換后的字符串長度 13 // 然后從后向前替換 14 void replaceSpace(char *str, int length) 15 { 16 if(length <= 0 || str == nullptr) 17 return ; 18 19 int space_count = 0; 20 for(int i = 0; i < length; i++) 21 { 22 if (str[i] == ' ') 23 space_count++; 24 } 25 26 int i = length-1; //替換前最后一個字符下標 27 int j = length+space_count*2-1; // 替換后最后一個字符的下標 28 while(j >= 0) 29 { 30 if (str[i] == ' ') 31 { 32 str[j--] = '0'; 33 str[j--] = '2'; 34 str[j--] = '%'; 35 i--; 36 } 37 else 38 str[j--] = str[i--]; 39 } 40 } 41 }; 42 43 44 int main(void) 45 { 46 char str[] = "as df kls"; 47 // char str[] = "hello"和char *str = "hello"不一樣 48 Solution s; 49 s.replaceSpace(str, strlen(str)); 50 return 0; 51 }