[CareerCup] 1.4 Replace Spaces 替換空格
阿新 • • 發佈:2018-12-29
1.4 Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end of the string to hold the additional characters, and that you are given the "true" length of the string. (Note: if implementing in Java, please use a character array so that you can perform this operation in place.)
這道題讓我們將一個字串裡所有的空格都替換為'%20',而且說明最好用in place的方法,就是說不要建新的字串。如果建個新的字元,那這題解法就顯得略low,因為那樣我們只需要遍歷原字串s,遇到字元直接加進來,遇到空格,直接加個'%20'就行了。這道題要使用高大上的in place的方法,那就是我們先便利一遍給定字串s,統計空格的個數,然後再resize一下字串,增大字串s的容量,以便我們來替換。然後我們再從原來s的末尾位置向開頭遍歷,遇到空格,在末尾三個空新增'%20',然後標示新位置,遇到非空格字元,則新增該字元,然後再標示新位置即可。程式碼如下:
class Solution {public: void replaceSpaces(string &s) { int count = 0, len = s.size(), newLen = 0; for (int i = 0; i < len; ++i) { if (s[i] == ' ') ++count; } newLen = len + 2 * count; s.resize(newLen); for (int i = len - 1; i >= 0; --i) {if (s[i] == ' ') { s[newLen - 1] = '0'; s[newLen - 2] = '2'; s[newLen - 3] = '%'; newLen -= 3; } else { s[newLen - 1] = s[i]; newLen -= 1; } } } };