-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0535-encode-and-decode-tinyurl.js
More file actions
46 lines (40 loc) · 1.3 KB
/
0535-encode-and-decode-tinyurl.js
File metadata and controls
46 lines (40 loc) · 1.3 KB
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
/**
* Encode And Decode Tinyurl
* Time Complexity: O(1)
* Space Complexity: O(N)
*/
class Solution {
constructor() {
this.shortToLongMapping = new Map();
this.longToShortMapping = new Map();
this.baseDomain = "http://tinyurl.com/";
this.urlIdentifierLength = 6;
this.characterSet =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
generateRandomIdentifier() {
let currentIdentifier = "";
for (let idx = 0; idx < this.urlIdentifierLength; idx++) {
const randomIndex = Math.floor(Math.random() * this.characterSet.length);
currentIdentifier += this.characterSet[randomIndex];
}
return currentIdentifier;
}
encode(originalLink) {
if (this.longToShortMapping.has(originalLink)) {
return this.longToShortMapping.get(originalLink);
}
let newShortenedLink;
let generatedIdentifier;
do {
generatedIdentifier = this.generateRandomIdentifier();
newShortenedLink = this.baseDomain + generatedIdentifier;
} while (this.shortToLongMapping.has(newShortenedLink));
this.shortToLongMapping.set(newShortenedLink, originalLink);
this.longToShortMapping.set(originalLink, newShortenedLink);
return newShortenedLink;
}
decode(shortenedLink) {
return this.shortToLongMapping.get(shortenedLink);
}
}