1. 程式人生 > >劍指Offer(書):替換空格

劍指Offer(書):替換空格

amp class har 補充 buffer space style col new

題目:請實現一個函數,將一個字符串中的每個空格替換成“%20”。例如,當字符串為We Are Happy.則經過替換之後的字符串為We%20Are%20Happy。

分析:通常來說,這樣的題有兩種方式。空間換時間,時間換空間。但是這個有更好的算法。可以先計算空格的次數,然後計算最後的長度,有兩個下標,分別表示原串最後的位置和結果串最後的位置,我們從後向前推,遇到空格就補充%20,同時結果串的下標依次前移,遇不到就將原串的當前下標的值給結果串下標的值,同時兩者下標前移,直到原串下標移到開始位置

public class Solution05 {
    public String replaceSpace(StringBuffer str) {
        
if (str == null) { return null; } if (str.length() == 0) { return str.toString(); } int spaceLength = 0; int strLength = str.length(); for (int i = 0; i < strLength; i++) { if (str.charAt(i) == ‘ ‘) { spaceLength
++; str.append(‘ ‘); str.append(‘ ‘); } } int resultLength = spaceLength * 2 + strLength - 1; for (int i = strLength - 1; i >= 0 && spaceLength > 0; i--) { if (str.charAt(i) == ‘ ‘) { str.setCharAt(resultLength,
‘0‘); resultLength--; str.setCharAt(resultLength, ‘2‘); resultLength--; str.setCharAt(resultLength, ‘%‘); resultLength--; spaceLength--; } else { str.setCharAt(resultLength--, str.charAt(i)); } } return str.toString(); } public static void main(String[] args) { Solution05 solution05 = new Solution05(); System.out.print(solution05.replaceSpace(new StringBuffer("We Are Happy. "))); } }

劍指Offer(書):替換空格