时间复杂度:O(n) */ classSolution { public: string replaceSpace(string str){ int length = str.size(); int spaceCount = 0; for (int i = 0; i < length; i ++) { if (str[i] == ' ') spaceCount ++; }
int newLength = length + spaceCount * 2; str.resize(newLength); for (int i = length - 1; i >= 0 && newLength != i; i --) { // i = newLen,说明前面已经没有空格了 if (str[i] != ' ') str[--newLength] = str[i]; else { str[--newLength] = '0'; str[--newLength] = '2'; str[--newLength] = '%'; } } return str; } };