題目: 實現一個函數,將字串中的空格替換為「%20」。例如輸入 "We Are Happy",輸出 "We%20Are%20Happy"。
替換後字串長度增加(每個空格 +2 字元)。若從前往後替換,需不斷移動後續字元,時間複雜度退化為 O(N²)。
最優解:從後往前雙指針原地替換,時間 O(N)、額外空間 O(1)(假設字串緩衝區足夠大)。
spaceCountnewLength = oldLength + spaceCount * 2i = oldLength - 1(舊尾)、j = newLength - 1(新尾)str[i] != ' ':str[j--] = str[i--]str[i] == ' ':str[j--] = '0'; str[j--] = '2'; str[j--] = '%'; i--public class Solution {
public String replaceSpace(StringBuffer str) {
int spaceCount = 0;
// 1. 統計空格數
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') spaceCount++;
}
int oldIdx = str.length() - 1;
int newIdx = str.length() + spaceCount * 2 - 1;
// 擴容 StringBuffer 到新長度
str.setLength(newIdx + 1);
// 2. 從後往前填充
for (int i = oldIdx; i >= 0; i--) {
char c = str.charAt(i);
if (c != ' ') {
str.setCharAt(newIdx--, c);
} else {
str.setCharAt(newIdx--, '0');
str.setCharAt(newIdx--, '2');
str.setCharAt(newIdx--, '%');
}
}
return str.toString();
}
}
輸入: "We Are Happy"
輸出: "We%20Are%20Happy"

此題考察雙指針技巧與原地修改數組的基本功,是字串操作類面試題的經典入門。