Title comes from force buckle:
String compression. Use the number of characters to repeat the number of times to write a method to achieve basic string compression function. For example, a string AABCCCCCAAA will become A2B1C5A3. If the string after “compression” does not shorten, the original string is returned. You can assume that the string contains only a lowercase English letters (A to Z).
# I wrote myself class solution: DEF Compressstring (Self, S: STR) -> STR: s = '' n1 = len (s) k = 1 # if n1 == 1 or n1 == 0: Return S else: for I in Range (1, N1): if s [i] == s [i-1]: k = k+1 #Considering the same situation after the string if i == n1-1: s = s + s [i-1] + str (k) else: s = s + s [i-1] + str (k) k = 1 #Considering the same situation after the string if i == n1-1: s = s + s [i] + str (1) n2 = len (s) if n1> n2: Return S else: Return S
This topic I debugged for two hours, mainly because I did not prepare the preliminary preparation: divide the boundary, find no different situations
The following method is the answer to the big boss, which is simpler than me above. The cleverness is to expand one string length first, so that there is no need to consider the condition of the string tail boundary.
class Solution: def compressString(self, S: str) -> str: ans = "" S += " " count = 1 for i in range(1, len(S)): if S[i] != S[i-1]: ans += S[i-1] + str(count) count = 1 else: count += 1 return ans if len(ans) < len(S)-1 else S[:-1]