4.替换空格 ----《剑指Offer》题解

题目

请实现一个函数,把字符串中的每个空格替换成"%20"。

你可以假定输入字符串的长度最大是1000。
注意输出字符串的长度可能大于1000。

样例
输入:"We are happy."

输出:"We%20are%20happy."

算法思路

常规思路是从前往后遍历,如果遇到空格,则将空格之后的所有数据移动两个位置,然后设置"%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();
    }
}

猜你喜欢

转载自www.cnblogs.com/TatuCz/p/11115433.html
今日推荐