43 lines
726 B
Markdown
43 lines
726 B
Markdown
---
|
|
title: leetcode-compress-string-lcci
|
|
date: 2020-04-01 15:51:22
|
|
tags:
|
|
- leetcode
|
|
categories: leetcode
|
|
---
|
|
|
|
### 面试题 01.06. 字符串压缩
|
|
|
|
[题目](https://leetcode-cn.com/problems/compress-string-lcci/)
|
|
|
|
<!--more-->
|
|
|
|
|
|
|
|
遍历一遍字符串,遇到跟上一个字符不同的字符时记录上一个字符的重复长度。
|
|
|
|
|
|
|
|
```python
|
|
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
|
|
```
|
|
|