[LeetCode] String Compression 字符串壓縮

 

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

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

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.post

 

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

 

Example 1:spa

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:code

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:htm

  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的值就是新數組的長度,直接返回便可。blog

具體來看代碼,咱們用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 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索