Skip to content

Commit 497ae21

Browse files
authored
count repeating chars
1 parent cca9b2d commit 497ae21

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

daily_coding_problems/problem_29

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
Daily Coding Problem #29
2+
Problem
3+
This problem was asked by Amazon.
4+
5+
Run-length encoding is a fast and simple method of encoding strings. The basic idea is to represent repeated successive characters as a single count and character. For example, the string "AAAABBBCCDAA" would be encoded as "4A3B2C1D2A".
6+
7+
Implement run-length encoding and decoding. You can assume the string to be encoded have no digits and consists solely of alphabetic characters. You can assume the string to be decoded is valid.
8+
9+
Solution
10+
We can implement encode by iterating over our input string and keeping a current count of whatever the current character is, and once we encounter a different one, appending the count (as a string) and the actual character to our result string.
11+
12+
def encode(s):
13+
if not s:
14+
return ''
15+
16+
result = ''
17+
current_char = s[0]
18+
current_count = 0
19+
for i, char in enumerate(s, 1):
20+
if char == current_char:
21+
current_count += 1
22+
else:
23+
result += str(current_count) + current_char
24+
current_char = char
25+
current_count = 1
26+
result += str(current_count) + current_char
27+
return result
28+
We can implement decode by iterating over the encoded string and checking each character for a digit. If it is, then calculate the correct count, and once we find its corresponding character, extend the result with the character count number of times and then reset the count.
29+
30+
def decode(s):
31+
count = 0
32+
result = ''
33+
for char in s:
34+
if char.isdigit():
35+
count = count * 10 + int(char)
36+
else:
37+
# char is alphabetic
38+
result += char * count
39+
count = 0
40+
return result

0 commit comments

Comments
 (0)