Skip to content

Commit 3b8d1e9

Browse files
committed
Create 0535-encode-and-decode-tinyurl.kt
1 parent 9a478df commit 3b8d1e9

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Codec() {
2+
3+
//to shorten URL
4+
val encodeMap = HashMap<String, String>()
5+
//to unshorten URL
6+
val decodeMap = HashMap<String, String>()
7+
val encodeCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
8+
val tinyUrl = "http://tinyurl.com/"
9+
10+
// Encodes a URL to a shortened URL.
11+
fun encode(longUrl: String): String {
12+
if(longUrl in encodeMap) return encodeMap[longUrl]!!
13+
var fakeHashCode = ""
14+
repeat(6) {
15+
fakeHashCode += encodeCharacters.random()
16+
}
17+
val encodedLongUrl = "${tinyUrl}${fakeHashCode}"
18+
encodeMap[longUrl] = encodedLongUrl
19+
decodeMap[encodedLongUrl] = longUrl
20+
return encodedLongUrl
21+
}
22+
23+
// Decodes a shortened URL to its original URL.
24+
fun decode(shortUrl: String): String {
25+
//since we are guaranteed that the shortUrl has been encoded
26+
return decodeMap[shortUrl]!!
27+
}
28+
}
29+
30+
/**
31+
* Your Codec object will be instantiated and called as such:
32+
* var obj = Codec()
33+
* var url = obj.encode(longUrl)
34+
* var ans = obj.decode(url)
35+
*/

0 commit comments

Comments
 (0)