题意:
给定一组字符,使用原地算法将其压缩。
压缩后的长度必须始终小于或等于原数组长度。
数组的每个元素应该是长度为1 的字符(不是 int 整数类型)。
在完成原地修改输入数组后,返回数组的新长度。
- !!!!而且要修改原list 大坑!!!!!
思路:双指针遍历即可
code:
class Solution:
def compress(self, chars: List[str]) -> int:
l, r, lenc = 0, 0, len(chars)
now = 0
while r < lenc:
chars[now] = chars[l]
now += 1
while r < lenc and chars[l] == chars[r]:
r += 1
temp = r - l
if temp > 1:
ans = []
while temp > 0:
ans.append(temp % 10)
temp //= 10
ans.reverse()
for i in ans:
chars[now] = str(i)
now += 1
l = r
chars = chars[0:now]
return len(chars)