leetcode 面试题 01.06. Compress String LCCI 字符串压缩
leetcode 2020年3月 每日一题打卡
程序员面试金典
题目: 字符串压缩。利用字符重复出现的次数,编写一种方法,实现基本的字符串压缩功能。比如,字符串aabcccccaaa会变为a2b1c5a3。若“压缩”后的字符串没有变短,则返回原先的字符串。你可以假设字符串中只包含大小写英文字母(a至z)。
示例1:
输入:“aabcccccaaa”
输出:“a2b1c5a3”
示例2:
输入:“abbccd”
输出:“abbccd”
解释:“abbccd"压缩后为"a1b2c2d1”,比原字符串长度更长。
提示:
字符串长度在[0, 50000]范围内。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/compress-string-lcci
思路: python
细节:
- list 获取最后一个值: list[-1]
- list转str: “”.join(list)
代码:
class Solution(object):
def compressString(self, S):
"""
:type S: str
:rtype: str
"""
l=len(S)
tem=0
ans=[]
for i in range(0,l):
if tem==0:
ans.append(S[i])
tem=1
continue
if tem!=0:
if S[i]==ans[-1]:
tem+=1
continue
else:
ans.append(str(tem))
ans.append(S[i])
tem=1
continue
ans.append(str(tem))
ansl=len(ans)
if ansl>=l:
return S
else:
return "".join(ans)
本博客为原创作品,欢迎指导,转载请说明出处,附上本文链接,谢谢!