726 B
726 B
| title | date | tags | categories | |
|---|---|---|---|---|
| leetcode-compress-string-lcci | 2020-04-01 15:51:22 |
|
leetcode |
面试题 01.06. 字符串压缩
遍历一遍字符串,遇到跟上一个字符不同的字符时记录上一个字符的重复长度。
class Solution:
def compressString(self, S: str) -> str:
if not S:
return S
c = ''
prev = S[0]
p_len = 1
for w in S[1:]:
if w != prev:
c += '%s%s' % (prev, p_len)
prev = w
p_len = 1
else:
p_len += 1
c += '%s%s' % (prev, p_len)
if len(S) > len(c):
return c
return S
# 52 ms 13.8 MB