Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
字符串压缩,方式如下:


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)

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理