剑指offer—05

  • Post author:
  • Post category:其他



剑指 Offer 05. 替换空格

请实现一个函数,把字符串

s

中的每个空格替换成”%20″。


示例 1:

输入:s = "We are happy."
输出:"We%20are%20happy."


限制:


0 <= s 的长度 <= 10000

class Solution {
    public String replaceSpace(String s) {
        //声明替换后字符串的存储位置
        StringBuilder s_new = new StringBuilder();

        for(int i = 0; i < s.length(); i ++){
            if(s.charAt(i) == ' '){
                s_new.append("%20");
            }else{
                s_new.append(s.charAt(i));
            }
        }

        return s_new.toString();
    }
}


https://www.runoob.com/java/java-stringbuffer.html

class Solution {
    public String replaceSpace(String s) {

        //声明新的char数组,将元素依次放入后转为String
        char[] array = new char [s.length() * 3];

        //标记替换后的有效位
        int arr_size = 0;

        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == ' '){
                array[arr_size] = '%';
                arr_size ++;
                array[arr_size] = '2';
                arr_size ++;
                array[arr_size] = '0';
                arr_size ++;
            }else{
                array[arr_size] = s.charAt(i);
                arr_size ++;
            }
        }

        //声明新的字符串,将最终的字符数组(有效长度为0-arr_size)转换为字符串输出
        String str_new = new String(array, 0, arr_size);
        return str_new.toString();
    }
}


https://blog.csdn.net/baidu_33604078/article/details/78954704



版权声明:本文为qq_34176797原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。