-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencode_decode_tiny_url.py
More file actions
41 lines (31 loc) · 1014 Bytes
/
encode_decode_tiny_url.py
File metadata and controls
41 lines (31 loc) · 1014 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 535. Encode and Decode TinyURL
# https://leetcode.com/problems/encode-and-decode-tinyurl
import unittest
class Codec:
def __init__(self):
self.hash_dic = {}
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
key = hash(longUrl)
self.hash_dic[str(key)] = longUrl
return 'http://tinyurl.com/' + str(key)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.hash_dic[shortUrl.replace('http://tinyurl.com/', '')]
class TestCodec(unittest.TestCase):
def test(self):
# Your Codec object will be instantiated and called as such:
codec = Codec()
url = 'https://leetcode.com/problems/design-tinyurl'
self.assertEqual(
codec.decode(codec.encode(url)),
url
)
if __name__ == '__main__':
unittest.TestCase()