題目描述:
請實現一個函數,將一個字符串中的空格替換成”%20”。例如,當字符串爲We Are Happy,則經過替換之後的字符串爲We%20Are%20Happy。
思路:
一組單詞不是有空格嘛,所以直接使用String類的split函數直接分割爲char數組不就好了,不過在這之前需要判斷一下第一個位置和最後一個位置是否有空格,然後針對空格的出現情況再進行替換。發現OJ的時候,如你所猜,自然是失敗的。因爲我忽略一個問題,就是如果一個句子中都是空格,調用split函數之後會發生什麼,會是一組空串。那麼根據題目要求,應該全部替換成%20纔對。所以這種思路被斃掉了。
於是,我尋找下一種思路,聯想到從尾部循環替換的思想(在冒泡排序算法之中也是從尾部往前進行比較然後交換的),於是形成如下的思路:首先統計出該字符串中所有的空格數量,並重新計算新串所需的char數組的長度,把舊串轉化成的char數組拷貝到一個臨時數組中,並同時創建一個新的char數組,該新數組的長度是計算之後的長度。從該新數組的尾部開始循環,依次往前比較,只要遇到了空格就替換爲%20。如果沒有遇到空格就直接複製過來就行。
代碼實現:
public class ReplaceSpace {
public String replaceSpace(StringBuffer str) {
String s = str.toString();
//統計空格數
int count = getBlankNum(str.toString());
//獲取原來字符串的長度
int originalStrLen = s.toCharArray().length;
//計算替換空格之後需要的長度
int newStrLen = count * 2 + originalStrLen;
char[] tempArray = new char[newStrLen];
//把原字符串複製到tempArray數組中
System.arraycopy(s.toCharArray(), 0, tempArray, 0, originalStrLen);
int originalStrIndex = originalStrLen - 1;
int newStrIndex = newStrLen -1;
//當originalStrIndex == newStrIndex的時候替換完畢
while(originalStrIndex >= 0 && originalStrIndex != newStrIndex){
if(tempArray[originalStrIndex] == ' '){
tempArray[newStrIndex--] = '0';
tempArray[newStrIndex--] = '2';
tempArray[newStrIndex--] = '%';
}else{
tempArray[newStrIndex--] = tempArray[originalStrIndex];
}
originalStrIndex--;
}
return new String(tempArray);
}
/**
* 計算空格數
* @param string
* @return
*/
private int getBlankNum(String string) {
int count = 0;
for (int i = 0; i < string.length(); i++) {
if(string.charAt(i) == ' '){
count++;
}
}
return count;
}
至此,劍指offer已經完成。