题目叙述:
Given an array of characters, compress it in-place.
The length after compression must always be smaller than or equal to the original array.
Every element of the array should be a character (not int) of length 1.
After you are done modifying the input array in-place, return the new length of the array.
class Solution:
def compress(self, chars: List[str]) -> int:
if len(chars)==0 or len(chars)==1:
return len(chars)
now = chars[0]
count = 1
countchar = -1
counter = 0
for i in range(1,len(chars)):
if chars[i] == now:
count+=1
if (i ==len(chars)-1):
countchar+=1
chars[countchar] = now
countchar2 = countchar+1
if count>1:
while(count):
counter +=1
remain = count%10
count = count//10
countchar+=1
chars[countchar] = str(remain)
#翻转部分列表
chars[countchar2:countchar2+counter] = chars[countchar2+counter-1:countchar2 -1:-1]
counter=0
else:
countchar+=1
chars[countchar] = now
countchar2 = countchar+1
if count>1:
while(count):
counter +=1
remain = count%10
count = count//10
countchar+=1
chars[countchar] = str(remain)
#翻转部分列表
chars[countchar2:countchar2+counter] = chars[countchar2+counter-1:countchar2 -1:-1]
counter=0
now = chars[i]
count = 1
if i == len(chars)-1:
countchar+=1
chars[countchar] = now
print(chars)
num = countchar+ 1
print(num)
return num