剑指Offer(书):替换空格

题目:请实现一个函数,将一个字符串中的每个空格替换成“%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. ")));
    }
}
原文地址:https://www.cnblogs.com/liter7/p/9416514.html