Skip to content

Instantly share code, notes, and snippets.

@humbroll
Created August 7, 2016 05:29
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 humbroll/183d75c8cb7f6ebc9f282664bd6ecd8a to your computer and use it in GitHub Desktop.
Save humbroll/183d75c8cb7f6ebc9f282664bd6ecd8a to your computer and use it in GitHub Desktop.
String Compression
#!/usr/bin/env python
# String Compression
# Implement a method to perform basic string compression using the counts of repeated characters.
# For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not
# become smaller than the original string, your method should return the original string.
# You can assume the string has only uppercase and lowercase letters(a-z)
import sys
SAMPLE_INPUT = "aabcccccaaa"
class StringCompression:
def __init__(self, org_str):
self.org_str = org_str
def run_compression(self):
org_str_len = len(self.org_str)
result = ""
current_char = self.org_str[0]
count_char = 1
for i, c in enumerate(self.org_str):
c = c.lower()
if c != current_char or i == (org_str_len - 1):
result += ("%s%d" % (current_char, count_char))
current_char = c
count_char = 1
elif c == current_char:
count_char += 1
if len(result) > org_str_len:
result = self.org_str
return result
def run_compression_v2(self):
pass
# We can optimize the logic with bit operation
if __name__ == '__main__':
input_value = sys.argv[1] if len(sys.argv) > 1 else SAMPLE_INPUT
string_compression = StringCompression(input_value)
result_value = string_compression.run_compression()
print "%s is compressed to %s" % (input_value, result_value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment