Created
June 18, 2014 03:10
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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