File tree 1 file changed +44
-1
lines changed
algorithms/EncodeAndDecodeTinyurl
1 file changed +44
-1
lines changed Original file line number Diff line number Diff line change 1
1
# 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
+ ```
You can’t perform that action at this time.
0 commit comments