diff options
author | Jack Sangdahl <[email protected]> | 2025-01-08 17:22:01 +0100 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-01-08 17:22:01 +0100 |
commit | 04d1609e0d5f554d23c19bc0629d0c3d697a87a1 (patch) | |
tree | 64bab4b0e844dcdd158525aac0691d36d1e8bf4d /encode_decode_tinyurl.py | |
parent | f416afbe5c617eb8aeae025d0b2d73c60145dbd3 (diff) | |
download | leetcode-04d1609e0d5f554d23c19bc0629d0c3d697a87a1.tar.gz leetcode-04d1609e0d5f554d23c19bc0629d0c3d697a87a1.zip |
535. encode and decode tinyurl
Diffstat (limited to 'encode_decode_tinyurl.py')
-rw-r--r-- | encode_decode_tinyurl.py | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/encode_decode_tinyurl.py b/encode_decode_tinyurl.py new file mode 100644 index 0000000..c043ba0 --- /dev/null +++ b/encode_decode_tinyurl.py @@ -0,0 +1,46 @@ +# 535. Encode and Decode TinyURL +from string import ascii_letters +from random import choice + +""" +tinyurl is a url shortening service where you enter a url such as +https://looooooongurl.com and it returns a short url such as +http://tinyurl.com/4e9iAk. design a class to encode a url and decode a tiny +url. there is no restriction on how your encode/decode algorithm should work. +you just need to ensure that a url can be encoded to a tiny url and the tiny +url can be decoded to the original url. +""" + + +class Codec: + alphabet = ascii_letters + "0123456789" + + def __init__(self): + self.url_code = {} + self.code_url = {} + + def encode(self, longUrl): + """Encodes a URL to a shortened URL. + + :type longUrl: str + :rtype: str + """ + while longUrl not in self.url_code: + code = "".join(choice(Codec.alphabet) for _ in range(6)) + if code not in self.code_url: + self.code_url[code] = longUrl + self.url_code[longUrl] = code + return "http://tinyurl.com/" + self.url_code[longUrl] + + def decode(self, shortUrl): + """Decodes a shortened URL to its original URL. + + :type shortUrl: str + :rtype: str + """ + return self.code_url[shortUrl[-6:]] + + +if __name__ == "__main__": + obj = Codec() + print(obj.decode(obj.encode("https://leetcode.com/problems/design-tinyurl"))) |