Skip to content

Instantly share code, notes, and snippets.

@danielcodes
Created April 6, 2020 13:47
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 danielcodes/1013882fa970ab04073b572bfbd1eb4d to your computer and use it in GitHub Desktop.
Save danielcodes/1013882fa970ab04073b572bfbd1eb4d to your computer and use it in GitHub Desktop.
271. Encode and decode strings
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