程序员@IT·互联网

剑指offer题解之二——替换空格

2016-08-15  本文已影响160人  KaelQ

1.题目

2.思路

3.code

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 newLength=str.length()+spaceNum*2;
        int oldLength=str.length()-1;
        str.setLength(newLength);
        newLength=newLength-1;
        for(;oldLength>=0&&oldLength<newLength;--oldLength){
            if(str.charAt(oldLength)==' '){
                str.setCharAt(newLength,'0');
                newLength--;
                str.setCharAt(newLength,'2');
                newLength--;
                str.setCharAt(newLength,'%');
                newLength--;
                
            }else{
                str.setCharAt(newLength,str.charAt(oldLength));
                newLength--;
            }
        }
        return str.toString();
    }
}
public class Solution {
    public String replaceSpace(StringBuffer str) {
        String s=str.toString();
        s=s.replace(" ","%20");
        return s;
    }
}

运行时间:23ms
占用内存:8664k

public class Solution {
    public String replaceSpace(StringBuffer str) {
        String after="";
        int a=0;
        while(a<str.length()){
            if(str.charAt(a)==' '){
                after=after+"%20";
            }else{
                after=after+str.charAt(a);
            }
            a++;
        }
        return after;
    }
}

运行时间:31ms
占用内存:15348k

public class Solution {
    public String replaceSpace(StringBuffer str) {
        int a=0;
        if(str.length()==1&& str.charAt(0)==' '){
            return "%20";
        }
        while(a<str.length()){
            if(str.charAt(a)==' '){
               str.append(str.charAt(str.length()-2));
               str.append(str.charAt(str.length()-1));
               for(int b=str.length()-1;b>a+2;b--){
                  str.setCharAt(b,str.charAt(b-2));
               }
               str.setCharAt(a,'%');
               str.setCharAt(a+1,'2');
               str.setCharAt(a+2,'0');
            }
            a++;
        }
        return str.toString();
    }
}

运行时间:31ms
占用内存:21964k

上一篇下一篇

猜你喜欢

热点阅读