-
Notifications
You must be signed in to change notification settings - Fork 154
/
Copy pathencode-and-decode-tinyurl.js
75 lines (65 loc) · 1.66 KB
/
encode-and-decode-tinyurl.js
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
/**
* Encode and Decode 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 the encode and decode methods for the TinyURL service.
* 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.
*/
/**
* Base62 Solution
*/
class TinyUrl {
constructor() {
this.database = {};
this.id = 0;
}
idToShortUrl(n) {
const map = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let shortUrl = '';
while (n) {
shortUrl = map[n % 62] + shortUrl;
n = Math.floor(n / 62);
}
return shortUrl;
}
shortUrlToId(shortUrl) {
let id = 0;
for (let c of shortUrl) {
if ('a' <= c && c <= 'z') {
id = id * 62 + c.charCodeAt(0) - 'a'.charCodeAt(0);
} else if ('A' <= c && c <= 'Z') {
id = id * 62 + c.charCodeAt(0) - 'A'.charCodeAt(0) + 26;
} else {
id = id * 62 + c.charCodeAt(0) - '0'.charCodeAt(0) + 52;
}
}
return id;
}
/**
* Encodes a URL to a shortened URL.
*
* @param {string} longUrl
* @return {string}
*/
encode(longUrl) {
const shortUrl = this.idToShortUrl(this.id);
this.database[this.id++] = longUrl;
return shortUrl;
}
/**
* Decodes a shortened URL to its original URL.
*
* @param {string} shortUrl
* @return {string}
*/
decode(shortUrl) {
const id = this.shortUrlToId(shortUrl);
return this.database[id];
}
}