4.替換空格 ----《劍指Offer》題解(Java)

題目

請實現一個函數,把字符串中的每一個空格替換成"%20"。算法

你能夠假定輸入字符串的長度最大是1000。
注意輸出字符串的長度可能大於1000。app

樣例
輸入:"We are happy."函數

輸出:"We%20are%20happy."code

算法思路

常規思路是從前日後遍歷,若是遇到空格,則將空格以後的全部數據移動兩個位置,而後設置"%20"。但這樣會由於移動數據次數過多而增長時間複雜度。
能夠先計算出空格的個數countOfBlank,從而得出新字符串的長度是n + 2*countOfBlank,而後設置字符串的長度爲新的長度。接着進行移動字符,從後往前遍歷字符串,依次複製字符到最終位置,遇到空格,則填充"%20"。
時間複雜度是O(n),n是字符串長度字符串

代碼實現

class Solution {
    public String replaceSpaces(StringBuffer str) {
        if (str == null) return null;

        int countOfBlank = 0;
        int oldLength = str.length();
        for(int i=0; i<str.length(); i++) {
            if (str.charAt(i) == ' ') countOfBlank++;
        }

        int newLength = str.length() + 2 * countOfBlank;
        str.setLength(newLength);
        int oldIndex = oldLength - 1;
        int newIndex = newLength - 1;
        //從後往前遍歷
        while (oldIndex >= 0 && newIndex >= 0) {
            if (str.charAt(oldIndex) == ' ') {
                str.setCharAt(newIndex--, '0');
                str.setCharAt(newIndex--, '2');
                str.setCharAt(newIndex--, '%');
                 
            } else {
                str.setCharAt(newIndex, str.charAt(oldIndex));
                newIndex--;
            }
            oldIndex--;
        }

        return str.toString();
    }
}
相關文章
相關標籤/搜索