剑指offer的题解——5.替换空格

剑指offer的题解——5.替换空格

题目:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。

最直观的做法是从头扫到尾,每次碰到空格时进行替换。于是把1个字符替换成3个字符,就必须要把空格后面的所有字符都后移2字节。假设字符串长度为n,对每个空格字符需要移动后面O(n)个字符,因此对于含有O(n)个空格字符的字符串而言,总的时间效率是O(n^2)。所以换种思路,从后向前替换。

Java实现代码:
思路一:开辟新的字符串。

	public static String replaceSpace1(StringBuffer str) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) != ' ') {
                buf.append(str.charAt(i));
            } else {
                buf.append("%20");
            }
        }
        return buf.toString();
    }

思路二:
不开辟新字符串,从后向前替换
1、从前往后替换,后面的字符不断往后移动,需要多次移动 时间复杂度是O(n^2)级别的。
2、从后往前替换,先计算需要多少空间,然后从后向前移动 则每个字符只移动一次,这样效率更高 步骤:
1、将str转成字符数组,也可直接使用stringbuffer的charAt(index)方法来处理
2、统计空格长度
3、计算新数组长度 ,并创建新数组
5、两个index,一个指向原长度在最后,一个指向新长度最后
6、从后向前判断第一个索引是否为空格,
若不为空格,将该索引值赋给第二个索引位置的值 若为空格,将第二个索引处开始赋值 一定注意索引值和位置的关系

	public static String replaceSpace2(StringBuffer str) {
        /*
         * 第二种方式 使用转成字符串数组
         */
        char[] a = str.toString().toCharArray();
        int spaceNum = 0;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == ' ')
                spaceNum++;
        }
        int newLength = (a.length + spaceNum * 2) - 1;
        char[] b = new char[newLength + 1]; //创建替换后的数组
        for (int i = a.length - 1; i >= 0; i--) { //从后向前遍历
            if (a[i] == ' ') {
                b[newLength--] = '0';
                b[newLength--] = '2';
                b[newLength--] = '%';

            } else {
                b[newLength--] = a[i];
            }
        }
        return String.valueOf(b);
    }
public static String replaceSpace4(StringBuffer str) {
		/*
         * 第二种方式 直接使用StringBuffer的charAt()方法
         */
        int spaceNum = 0;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ')
                spaceNum++;
        }
        int aIndex = str.length() - 1;
        str.setLength(str.length() + spaceNum * 2);
        int bIndex = aIndex + spaceNum * 2;
        for (int i = aIndex; i >= 0; i--) { //原字符串从后向前遍历到第一个
            if (str.charAt(i) == ' ') {
                str.setCharAt(bIndex--, '0');
                str.setCharAt(bIndex--, '2');
                str.setCharAt(bIndex--, '%');
            } else {
                str.setCharAt(bIndex--, str.charAt(i));
            }
        }
        return str.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值