剑指offer(4) 替换空格

题目

  请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。

 

思路

  首先要询问面试官是新建一个字符串还是在原有的字符串上修改,本题要求在原有字符串上进行修改。

  若从前往后依次替换,在每次遇到空格字符时,都需要移动后面O(n)个字符,对于含有O(n)个空格字符的字符串而言,总的时间效率为O(n2)。

  转变思路:先计算出需要的总长度,然后从后往前进行复制和替换,,则每个字符只需要复制一次即可。时间效率为O(n)。

测试用例

  1.字符串中无空格

  2.字符串中含有空格(连续空格,空格在首尾等)

  3.字符串为空字符串或者为null

 

完整Java代码

public class ReplaceSpaces {
 
    /**
     * 实现空格的替换
     */
    public String replaceSpace(StringBuffer str) {
        if (str == null) {
            System.out.println("输入错误!");
            return null;
        }
        int length = str.length();
        int indexOfOriginal = length-1;
        for (int i = 0; i < str.length(); i++) {
            if (str.charAt(i) == ' ')
                length += 2;
        }
        str.setLength(length);
        int indexOfNew = length-1;
        while (indexOfNew > indexOfOriginal) {
            if (str.charAt(indexOfOriginal) != ' ') {
                str.setCharAt(indexOfNew--, str.charAt(indexOfOriginal));
            } else {
                str.setCharAt(indexOfNew--, '0');
                str.setCharAt(indexOfNew--, '2');
                str.setCharAt(indexOfNew--, '%');
            }
            indexOfOriginal--;
        }
        return str.toString();
    }
     
    // ==================================测试代码==================================
 
    /**
     * 输入为null
     */
    public void test1() {
        System.out.print("Test1:");
        StringBuffer sBuffer = null;
        String s = replaceSpace(sBuffer);
        System.out.println(s);
    }
     
    /**
     * 输入为空字符串
     */
    public void test2() {
        System.out.print("Test2:");
        StringBuffer sBuffer = new StringBuffer("");
        String s = replaceSpace(sBuffer);
        System.out.println(s);
    }
     
    /**
     * 输入字符串无空格
     */
    public void test3() {
        System.out.print("Test3:");
        StringBuffer sBuffer = new StringBuffer("abc");
        String s = replaceSpace(sBuffer);
        System.out.println(s);
    }
     
    /**
     * 输入字符串为首尾空格,中间连续空格
     */
    public void test4() {
        System.out.print("Test4:");
        StringBuffer sBuffer = new StringBuffer(" a b  c  ");
        String s = replaceSpace(sBuffer);
        System.out.println(s);
    }
     
    public static void main(String[] args) {
        ReplaceSpaces rs = new ReplaceSpaces();
        rs.test1();
        rs.test2();
        rs.test3();
        rs.test4();
    }
}
Test1:输入错误!
null
Test2:
Test3:abc
Test4:%20a%20b%20%20c%20%20

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值