剑指offer 05 替换空格(java)

替换空格

题目描述

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

注意输入类型,输入的str为StringBuffer,相关操作有设置长度,setCharAt()等,随后需要调用toString()返回。

方法一

直接在原数组上替换 :

时间O(N)
空间O(1)

public class Solution{
    public String replaceSpace(StringBuffer str){
        int count = 0;
        int len = str.length();
        for(int i = 0; i < len; i++){
            if(str.charAt(i) == ' '){
                count++;
            }
        }
        int newindex = len + count * 2 - 1;
        str.setLength(newindex +1); // 一定要重新设置长度!
        int oldindex = len - 1;
        while(newindex >= 0 && oldindex >=0 && newindex >oldindex) {
            if(str.charAt(oldindex) == ' '){
                str.setCharAt(newindex--, '0');
                str.setCharAt(newindex--, '2');
                str.setCharAt(newindex--, '%');
            }else{
                str.setCharAt(newindex--, str.charAt(oldindex));
            }
            oldindex--;
        }
        return str.toString();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章