Skip to content

Instantly share code, notes, and snippets.

@monkerek
Created June 18, 2014 03:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monkerek/b2051b2d48ccbcfe1db2 to your computer and use it in GitHub Desktop.
Save monkerek/b2051b2d48ccbcfe1db2 to your computer and use it in GitHub Desktop.
CC1.5 Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.
# idea: traverse the string directly and count #characters. Then check whether the result is smaller than input string.
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def StrCompression(self, string):
if string == '':
return string
ret = ''
pivot = string[0]
count = 1
for char in string[1:]:
if char == pivot:
count += 1
else:
ret += pivot + str(count)
pivot = char
count = 1
ret += pivot + str(count)
if len(ret) < len(string):
return ret
return string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment