Skip to content

Commit b29278e

Browse files
String Compression Done
1 parent 08821a4 commit b29278e

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
String Compression: Implement a method to perform basic string compression using the counts
3+
of repeated characters. For example, the string aabcccccaaa would become a2blc5a3, If the
4+
"compressed" string would not become smaller than the original string, your method should return
5+
the original string. You can assume the string has only uppercase and lowercase letters (a - z).
6+
Hints: #92, if 110
7+
8+
'''
9+
10+
from tokenize import String
11+
12+
13+
def Str_compress(s):
14+
comp_str = ""
15+
count_char = 1
16+
for i in range(len(s)): #if i is greater than zero
17+
if (i > 0 and s[i] == s[i-1]):
18+
count_char += 1
19+
elif(i > 0 and s[i] != s[i-1]):
20+
comp_str += s[i-1] + str(count_char)
21+
count_char = 1
22+
23+
final_str = comp_str + s[-1] + str(count_char) #handling last char of string
24+
if (len(final_str) > len(s)):
25+
return s
26+
else:
27+
return final_str
28+
29+
if __name__ == '__main__':
30+
s = input("Enter string >> ").strip()
31+
answer = Str_compress(s)
32+
print(answer)

0 commit comments

Comments
 (0)