[LeetCode] String Compression 字符串壓縮


 

Given an array of characters, compress it in-place.

The length after compression must always be smaller than or equal to the original array.

Every element of the array should be a character (not int) of length 1.

After you are done modifying the input array in-place, return the new length of the array.

 

Follow up:
Could you solve it using only O(1) extra space?

 

Example 1:

Input:
["a","a","b","b","c","c","c"]

Output:
Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation:
"aa" is replaced by "a2". "bb" is replaced by "b2". "ccc" is replaced by "c3".

 

Example 2:

Input:
["a"]

Output:
Return 1, and the first 1 characters of the input array should be: ["a"]

Explanation:
Nothing is replaced.

 

Example 3:

Input:
["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output:
Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Explanation:
Since the character "a" does not repeat, it is not compressed. "bbbbbbbbbbbb" is replaced by "b12".
Notice each digit has it's own entry in the array.

 

Note:

  1. All characters have an ASCII value in [35, 126].
  2. 1 <= len(chars) <= 1000.

 

這道題給了我們一個字符串,讓我們進行壓縮,即相同的字符統計出個數,顯示在該字符之后,根據例子分析不難理解題意。這道題要求我們進行in place操作,即不使用額外空間,最后讓我們返回修改后的新數組的長度。我們首先想,數組的字符不一定是有序的,如果我們用Map來建立字符和出現次數之間的映射,不管是用HashMap還是TreeMap,一定無法保證原有的順序。所以不能用Map,而我們有需要統計個數,那么雙指針就是不二之選啦。既然雙指針,其中一個指針指向重復字符串的第一個,然后另一個指針向后遍歷並計數,就能得到重復的個數。我們仔細研究例子3,可以發現,當個數是兩位數的時候,比如12,這里是將12拆分成1和2,然后存入數組的。那么比較簡便的提取出各個位上的數字的辦法就是轉為字符串進行遍歷。另外,由於我們需要對原數組進行修改,則需要一個指針cur來標記下一個可以修改的位置,那么最終cur的值就是新數組的長度,直接返回即可。

具體來看代碼,我們用i和j表示雙指針,開始循環后,我們用j來找重復的字符串的個數,用一個while循環,最終j指向的是第一個和i指向字符不同的地方,此時我們需要先將i位置的字符寫進chars中,然后我們判斷j是否比i正好大一個,因為只有一個字符的話,后面是不用加個數的,所以直接跳過。否則我們將重復個數轉為字符串,然后提取出來修改chars數組即可,注意每次需要將i賦值為j,從而開始下一個字符的統計,參見代碼如下:

 

class Solution {
public:
    int compress(vector<char>& chars) {
        int n = chars.size(), cur = 0;
        for (int i = 0, j = 0; i < n; i = j) {
            while (j < n && chars[j] == chars[i]) ++j;
            chars[cur++] = chars[i];
            if (j - i == 1) continue;
            for (char c : to_string(j - i)) chars[cur++] = c;
        }
        return cur;
    }
};

 

類似題目:

Count and Say

Encode and Decode Strings

Design Compressed String Iterator

 

參考資料:

https://leetcode.com/problems/string-compression/discuss/118472/C++-simple-solution-(-EASY-to-understand-)-with-explanation

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM