【演算法】將字串中的空格替換成指定字串
阿新 • • 發佈:2018-11-18
題目:
字串中的空格替換成指定字串,如%20。
給定一個字串,內部有空格,請用最少的時間複雜度、空間複雜度,將空格替換為%20
示例:
輸入:
This is a test string
輸出:
This%20is%20a%20test%20%string
思路:
只建立所需的額外空間
採用逆序雙索引進行逐個移動,正序遍歷移動量較大。
關鍵點:
逆序處理,利用原記憶體空間,雙索引(或指標)
實現:
c++
#include <iostream> #include <string> using namespace std; class Solution{ public: // str: 輸入字串 // pad: 填充的字串 string replaceBlank(string str, string pad){ int padLen = pad.length(); int strLen = str.length(); int blankSize = 0; //統計空格個數 for(int i=0; i<strLen; i++){ if(str[i]==' ') blankSize ++; } //統計所需新增記憶體 int memNeed = (padLen-1) * blankSize; str += string(memNeed, ' '); int newIndex = str.length()-1; int oldIndex = strLen-1; //逆序迴圈 while(oldIndex>=0){ if(str[oldIndex]!=' '){ str[newIndex--] = str[oldIndex--]; }else{ //替換符逆序填補 for(int i=padLen-1; i>=0; i--){ str[newIndex--] = pad[i]; } oldIndex --; } } return str; } }; int main(){ string str = "This is a test"; string pad = "%20"; Solution slu = Solution(); string result = slu.replaceBlank(str, pad); cout << "input: " << str << endl; cout << "pad: " << pad << endl; cout << "output: " << result << endl; }