1. 程式人生 > >leetcode (String Compression)

leetcode (String Compression)

Title:String Compression  443

Difficulty:Easy

原題leetcode地址:https://leetcode.com/problems/string-compression

 

1.    雙指標

時間複雜度:O(n^2),巢狀迴圈,最長可能不需要到n^2。

空間複雜度:O(1),沒有申請額外空間。

    /**
     * 雙指標,一個指標指向重複字串的第一個,另一個指標向後遍歷並計數
     * 當計數是一位數時,不需要放入其中
     * 當計數是兩位數及兩位數以上,需要對這兩位數進行拆分
     * @param chars
     * @return
     */
    public static int compress(char[] chars) {

        int len = chars.length;
        int cur = 0;

        for (int i = 0, j =0; i < len; i = j) {
            while (j < len && chars[i] == chars[j]) {
                j++;
            }
            chars[cur++] = chars[i];
            if (j - i == 1) {
                continue;
            }
            for (char c : (j - i + "").toCharArray()) {
                chars[cur++] = c;
            }
        }

        return cur;

    }