替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成“%20”。

思路分析

  • 本题是考察对字符串的理解和应用,不建议直接调用相关的方法直接实现
  • 暴力法直接遍历查找,后移替换,但是复杂度O(n2)。
  • 复杂度为O(n)的方法:先遍历字符串,统计空格的个数,那么新的字符串长度为(空格 * 2  + 原长度),从尾部开始遍历,后移替换
  • 两个指针,一个指向新长度末尾,一个指向原始字符串

代码

public class Solution {
    public String replaceSpace(StringBuffer str) {
    	int spacenum = 0;
        for(int i=0; i < str.length(); i++){
            if(str.charAt(i) == ' '){
                spacenum++;
            }
        }
        int oldlength = str.length();
        int oldindex = oldlength - 1;
        int newlength = spacenum * 2 + oldlength;
        str.setLength(newlength);
        int newindex = newlength - 1;
        for(; oldindex >= 0 && oldlength < newlength; oldindex--){
            if (str.charAt(oldindex) == ' '){
                str.setCharAt(newindex--, '0');
                str.setCharAt(newindex--, '2');
                str.setCharAt(newindex--, '%');
            }
            else{
                str.setCharAt(newindex--, str.charAt(oldindex));
            }
        }
        return str.toString();
    }
}

  

posted @ 2020-04-11 12:59  Coding-Liu  阅读(158)  评论(0)    收藏  举报