Created
April 6, 2020 13:47
-
-
Save danielcodes/1013882fa970ab04073b572bfbd1eb4d to your computer and use it in GitHub Desktop.
271. Encode and decode strings
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
def encode(words): | |
ans = '' | |
# count-word is the encoding | |
for i in range(len(words)): | |
ans += str(len(words[i])) + '-' + words[i] | |
return ans | |
def decode(string): | |
length = 0 | |
start = 0 | |
base = 0 | |
ans = [] | |
while start < len(string): | |
if string[start].isdigit(): | |
# get the number out, increase base and start | |
length += base*10 + int(string[start]) | |
base += 1 | |
start += 1 | |
else: | |
# delimiter hit, grab string | |
begin = start+1 | |
ans.append(string[begin:begin+length]) | |
# reset, jump start and reset length and base | |
start = begin+length | |
length = 0 | |
base = 0 | |
return ans | |
words = ['church', 'kids', 'like', 'cake + ice cream'] | |
encoded = encode(words) | |
decoded = decode(encoded) | |
print('original', words) | |
print(encoded) | |
print(decoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment