56.4k views
0 votes
encode the original string by finding sequences in the string * where the same character repeats. replace each such sequence * by a token consisting of: the number of characters in the sequence * followed by the repeating character. * return the encoded string.

1 Answer

3 votes

Im gonna use python3 for this example

def encode(string):

if not string:

return string

new_string = []

last_char = ""

count = 1

for char in string:

if char == last_char:

new_string.pop(len(new_string)-1)

count += 1

elif char != last_char and count > 1:

new_string.append(str(count)+last_char)

count = 1

new_string.append(char)

last_char = char

else:

last_char = char

new_string.append(char)

return "".join(new_string)

print(encode("Hello There"))

User Darrin Holst
by
4.6k points