Posted on 2023-03-02 20:32
Uriel 閱讀(32)
評論(0) 編輯 收藏 引用 所屬分類:
閑來無事重切Leet Code
字符串壓縮,方式如下:
Input: chars = ["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"]
如果只出現一次,則不需要輸出1
不需要額外開一個list存儲壓縮后的字符串,直接chars一邊從左邊pop一邊后面append統計好字符+出現次數
1 #443
2 #Runtime: 38 ms (Beats 88.21%)
3 #Memory: 13.6 MB (Beats 94.34%)
4
5 class Solution(object):
6 def compress(self, chars):
7 """
8 :type chars: List[str]
9 :rtype: int
10 """
11 n = 0
12 l = len(chars)
13 for i in range(l):
14 ch = chars.pop(0)
15 if i == 0:
16 pre = ch
17 n = 1
18 chars.append(str(ch))
19 else:
20 if pre != ch:
21 if n > 1:
22 chars.extend([_ for _ in str(n)])
23 n = 1
24 chars.append(ch)
25 pre = ch
26 else:
27 n += 1
28 if n > 1:
29 chars.extend([_ for _ in str(n)])
30 return len(chars)