-
Notifications
You must be signed in to change notification settings - Fork 43
/
encode-and-decode-tinyurl.py
296 lines (250 loc) · 8.45 KB
/
encode-and-decode-tinyurl.py
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""
Note: This is a companion problem to the System Design problem: Design TinyURL.
TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl 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.
Implement the Solution class:
Solution() Initializes the object of the system.
String encode(String longUrl) Returns a tiny URL for the given longUrl.
String decode(String shortUrl) Returns the original long URL for the given shortUrl. It is guaranteed that the given shortUrl was encoded by the same object.
Example 1:
Input: url = "https://leetcode.com/problems/design-tinyurl"
Output: "https://leetcode.com/problems/design-tinyurl"
Explanation:
Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after deconding it.
Constraints:
1 <= url.length <= 104
url is guranteed to be a valid URL.
# REF : https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/
"""
# V0 : ARRAY
class Codec:
def __init__(self):
self.urls = []
def encode(self, longUrl):
self.urls.append(longUrl)
return "http://tinyurl.com/" + str(len(self.urls) - 1)
def decode(self, shortUrl):
return self.urls[int(shortUrl.split('/')[-1])]
# V0'
### TODO : optimize below via idea :
# https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/
# IDEA : DICT
class Codec:
def __init__(self):
self.prefix = "http://tinyurl.com/"
self.short_long = {}
self.long_short = {}
def encode(self, longUrl):
if longUrl not in self.long_short:
self.long_short[longUrl] = self.prefix + str(len(longUrl))
self.short_long[self.prefix + str(len(longUrl))] = longUrl
return self.prefix + str(len(longUrl))
def decode(self, shortUrl):
if shortUrl in self.short_long:
return self.short_long[shortUrl]
return False
# V0
# In [27]: import string
#
# In [28]: string.ascii_letters
# Out[28]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#
# In [29]: string.digits
# Out[29]: '0123456789'
class Codec:
import string
#letters = string.ascii_letters + string.digits
letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' + '0123456789'
full_tiny = {}
tiny_full = {}
global_counter = 0
def encode(self, longUrl):
def decto62(dec):
ans = ""
while 1:
ans = self.letters[dec % 62] + ans
dec //= 62
if not dec:
break
return ans
suffix = decto62(self.global_counter)
if longUrl not in self.full_tiny:
self.full_tiny[longUrl] = suffix
self.tiny_full[suffix] = longUrl
self.global_counter += 1
return "http://tinyurl.com/" + suffix
def decode(self, shortUrl):
idx = shortUrl.split('/')[-1]
if idx in self.tiny_full:
return self.tiny_full[idx]
else:
return None
# V0''
# IDEA : DICT
class Codec:
def __init__(self):
self.count = 0
self.d = dict()
def encode(self, longUrl):
self.count += 1
self.d[self.count] = longUrl
return str(self.count)
def decode(self, shortUrl):
return self.d[int(shortUrl)]
# V0''
import random
class Codec:
def __init__(self):
self.dic = {}
self.dic2 = {}
def encode(self, longUrl):
# Encodes a URL to a shortened URL.
self.dic[longUrl] = str(random.randint(1,100))
self.dic2["https://tinyurl.com/" + self.dic[longUrl]] = longUrl
return "https://tinyurl.com/" + self.dic[longUrl]
def decode(self, shortUrl):
# Decodes a shortened URL to its original URL.
return self.dic2[shortUrl]
# V1
# https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/
# C++
# string idToShortURL(long int n)
# {
# // Map to store 62 possible characters
# char map[] = "abcdefghijklmnopqrstuvwxyzABCDEF"
# "GHIJKLMNOPQRSTUVWXYZ0123456789";
#
# string shorturl;
#
# // Convert given integer id to a base 62 number
# while (n)
# {
# shorturl.push_back(map[n%62]);
# n = n/62;
# }
#
# // Reverse shortURL to complete base conversion
# reverse(shorturl.begin(), shorturl.end());
#
# return shorturl;
# }
#
# // Function to get integer ID back from a short url
# long int shortURLtoID(string shortURL)
# {
# long int id = 0; // initialize result
#
# // A simple base conversion logic
# for (int i=0; i < shortURL.length(); i++)
# {
# if ('a' <= shortURL[i] && shortURL[i] <= 'z')
# id = id*62 + shortURL[i] - 'a';
# if ('A' <= shortURL[i] && shortURL[i] <= 'Z')
# id = id*62 + shortURL[i] - 'A' + 26;
# if ('0' <= shortURL[i] && shortURL[i] <= '9')
# id = id*62 + shortURL[i] - '0' + 52;
# }
# return id;
# }
# V1'
# https://blog.csdn.net/fuxuemingzhu/article/details/79264976
# IDEA : ARRAY
class Codec:
def __init__(self):
self.urls = []
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.urls.append(longUrl)
return "http://tinyurl.com/" + str(len(self.urls) - 1)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.urls[int(shortUrl.split('/')[-1])]
# V1''
# https://blog.csdn.net/fuxuemingzhu/article/details/79264976
# IDEA : DICT
class Codec:
def __init__(self):
self.count = 0
self.d = dict()
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
self.count += 1
self.d[self.count] = longUrl
return str(self.count)
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
return self.d[int(shortUrl)]
# V1'''
# https://www.jiuzhang.com/solution/encode-and-decode-tinyurl/#tag-highlight-lang-python
import random
class Solution:
def __init__(self):
self.dic = {}
self.dic2 = {}
def encode(self, longUrl):
# Encodes a URL to a shortened URL.
self.dic[longUrl] = str(random.randint(1,100))
self.dic2["https://tinyurl.com/" + self.dic[longUrl]] = longUrl
return "https://tinyurl.com/" + self.dic[longUrl]
def decode(self, shortUrl):
# Decodes a shortened URL to its original URL.
return self.dic2[shortUrl]
# V1''''
# https://leetcode.com/problems/encode-and-decode-tinyurl/discuss/100341/Easy-to-Understand-in-Python
# string DEMO
# In [27]: import string
#
# In [28]: string.ascii_letters
# Out[28]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#
# In [29]: string.digits
# Out[29]: '0123456789'
class Codec:
import string
letters = string.ascii_letters + string.digits
full_tiny = {}
tiny_full = {}
global_counter = 0
def encode(self, longUrl):
"""Encodes a URL to a shortened URL.
:type longUrl: str
:rtype: str
"""
def decto62(dec):
ans = ""
while 1:
ans = self.letters[dec % 62] + ans
dec //= 62
if not dec:
break
return ans
suffix = decto62(self.global_counter)
if longUrl not in self.full_tiny:
self.full_tiny[longUrl] = suffix
self.tiny_full[suffix] = longUrl
self.global_counter += 1
return "http://tinyurl.com/" + suffix
def decode(self, shortUrl):
"""Decodes a shortened URL to its original URL.
:type shortUrl: str
:rtype: str
"""
idx = shortUrl.split('/')[-1]
if idx in self.tiny_full:
return self.tiny_full[idx]
else:
return None