Title:
Solution:
- After a string variable is provided to store the compressed temp1, calculation of a variable number of current occurrences of the letter count (initial value is 0);
- Temp1 initialized to S [0], count plus 1; cycles followed by the string S; and if the current character is equal to the previous character, the current character repetitions + 1; if not equal, then the current character temp1 was added, the current character set number string;
- Finally temp1 that is required of string compression.
code show as below:
class Solution:
def compressString(self, S):
if S == '':
return S
#定义一个临时存储的空间
temp1 = ''
count = 0
if temp1 == '':
temp1 += S[0]
count += 1
for i in range(1,len(S)):
if S[i] != S[i - count]:
temp1 += str(count)
temp1 += S[i]
count = 1
else:
count += 1
temp1 += str(count)
if len(temp1) < len(S):
return temp1
else:
return S