劍指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();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章