請實作一個函式,將一個字串中的每個空格替換成“%20”,例如,當字串為We Are Happy.則經過替換之后的字串為We%20Are%20Happy
解法一:直接呼叫函式
這種做法面試官看了直呼內行,然后反手把你掛了
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replaceAll(" " , "%20");
}
}
解法二:
構造一個新的字串,遍歷原字串,把字符依次挪到新字串,遇到空格就換成題目要求的新字符
public class Solution {
public String replaceSpace(StringBuffer str) {
StringBuffer newStr = new StringBuffer();
for(int i = 0; i < str.length(); i++) {
if(str.charAt(i) != ' ') {
newStr.append(str.charAt(i));
} else {
newStr.append("%20");
}
}
return newStr.toString();
}
}
解法三:
從前向后記錄空格的數目,從后向前替換空格
0 1 2 3 4 5 6 7 8 9 10 11
w e a r e l u c k y
假設空格的個數為 count,可以得知 count 為 2,所以在替換的時候,下標 7 ~ 11 的字母要向后移動 count × 2 個位置,3 ~ 5 字母要向后移動 (count - 1) × 2 個位置, 所以得到 :
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
w e a r e l u c k y
w e a r e l u c k y
這時就可以直接在空格處寫入 %20 了
public class Solution {
public String replaceSpace(StringBuffer str) {
// 計算空格數
int spaceCount = 0;
for(int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceCount++;
}
}
// 保存下標
int index = str.length() - 1;
// 擴大長度
str.setLength(str.length() + spaceCount*2);
while (index >= 0) {
if (str.charAt(index) != ' ') {
str.setCharAt(index + spaceCount * 2, str.charAt(index));
} else {
spaceCount--;
str.setCharAt(index + spaceCount * 2, '%');
str.setCharAt(index + spaceCount * 2 + 1, '2');
str.setCharAt(index + spaceCount * 2 + 2, '0');
}
index--;
}
return str.toString();
}
}
總結:字符替換類的題目,要大膽假設,不要覺得想法過于復雜就放棄思考
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/16233.html
標籤:其他
上一篇:0152. Maximum Product Subarray (M)
下一篇:GoLand 如何自動批量換行
