1. 程式人生 > >【劍指Offer程式設計題】替換空格 - JAVA

【劍指Offer程式設計題】替換空格 - JAVA

問題:

請實現一個函式,將一個字串中的每個空格替換成“%20”。例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。

 

思路:

1.計算出字串長度(old_len + (space_len * 2))
2.從新長度的最後一位往前放置字串內容,保證元素一次到達自己的位置

 

時間複雜度:

O(n)


/**
 * 請實現一個函式,將一個字串中的每個空格替換成“c”。
 * 例如,當字串為We Are Happy.則經過替換之後的字串為We%20Are%20Happy。
 */
public class Main {

    public static void main(String[] args) {
        Main main = new Main();
        StringBuffer s =new StringBuffer("We Are Happy");
        System.out.println(main.replaceSpace(s));

    }

    /**
     * 思路:
     * 1.計算出字串長度(old_len + (space_len * 2))
     * 2.從新長度的最後一位往前放置字串內容,保證元素一次到達自己的位置
     *
     * 時間複雜度:O(n)
     * @param str
     * @return
     */
    public String replaceSpace(StringBuffer str) {
        //原本長度
        int old_len = str.length();
        //空格長度
        int space_len = 0;
        for (int i = 0; i < old_len; i++) {
            if (str.charAt(i) == ' ') {
                space_len++;
            }
        }
        //設定新字串長度
        int new_len = old_len + (space_len * 2);
        str.setLength(new_len);

        //從最後一位往前移動
        int index_old = old_len - 1;//原字串索引
        int index_new = new_len - 1;//新字串索引
        while (index_new >=0) {
            //若該位置為空格
            if (str.charAt(index_old) == ' ') {
                str.setCharAt(index_new--, '0');
                str.setCharAt(index_new--, '2');
                str.setCharAt(index_new--, '%');
            }
            //否則該位置不為空格
            else {
                str.setCharAt(index_new--, str.charAt(index_old));
            }
            index_old--;
        }
        return str.toString();
    }
}