File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ */
You can’t perform that action at this time.
0 commit comments