首页 > 其他 > 详细

剑指Offer(书):替换空格

时间:2018-08-04 12:57:42      阅读:141      评论:0      收藏:0      [点我收藏+]

题目:请实现一个函数,将一个字符串中的每个空格替换成“%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(书):替换空格

原文:https://www.cnblogs.com/liter7/p/9416514.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!