Skip to content

Commit 6dab866

Browse files
committed
better solution of Encode And Decode Tinyurl
1 parent 46cd478 commit 6dab866

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed
Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,45 @@
11
# Encode And Decode Tinyurl
2-
We can solve this problem by hashmap
2+
We can solve this problem by hashmap, the better solution is like below:
3+
```python
4+
class Codec:
5+
def __init__(self):
6+
self.encode_url_map = {}
7+
self.url_encode_map = {}
8+
self.base_url = 'http://tinyurl.com/'
9+
self.encode_table = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
10+
11+
def encode(self, longUrl):
12+
"""Encodes a URL to a shortened URL.
13+
14+
:type longUrl: str
15+
:rtype: str
16+
"""
17+
if self.url_encode_map.get(longUrl):
18+
return self.base_url + self.url_encode_map.get(longUrl)
19+
20+
# i <= pow(62, 6) - 1
21+
i = len(self.encode_url_map)
22+
23+
encode = ''
24+
while i > 0:
25+
encode += self.encode_table[i % 62]
26+
i /= 62
27+
encode = encode.zfill(6)
28+
self.url_encode_map[longUrl] = encode
29+
self.encode_url_map[encode] = longUrl
30+
return self.base_url + encode
31+
32+
33+
def decode(self, shortUrl):
34+
"""Decodes a shortened URL to its original URL.
35+
36+
:type shortUrl: str
37+
:rtype: str
38+
"""
39+
encode = shortUrl.replace(self.base_url, '')
40+
return self.encode_url_map.get(encode)
41+
42+
# Your Codec object will be instantiated and called as such:
43+
# codec = Codec()
44+
# codec.decode(codec.encode(url))
45+
```

0 commit comments

Comments
 (0)