From 3b8d1e95fb05c91b8a2425d64b5c82bbb5575e82 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 28 Jan 2023 22:18:32 +0100 Subject: [PATCH] Create 0535-encode-and-decode-tinyurl.kt --- kotlin/0535-encode-and-decode-tinyurl.kt | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 kotlin/0535-encode-and-decode-tinyurl.kt diff --git a/kotlin/0535-encode-and-decode-tinyurl.kt b/kotlin/0535-encode-and-decode-tinyurl.kt new file mode 100644 index 000000000..1b65b2699 --- /dev/null +++ b/kotlin/0535-encode-and-decode-tinyurl.kt @@ -0,0 +1,35 @@ +class Codec() { + + //to shorten URL + val encodeMap = HashMap() + //to unshorten URL + val decodeMap = HashMap() + val encodeCharacters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + val tinyUrl = "http://tinyurl.com/" + + // Encodes a URL to a shortened URL. + fun encode(longUrl: String): String { + if(longUrl in encodeMap) return encodeMap[longUrl]!! + var fakeHashCode = "" + repeat(6) { + fakeHashCode += encodeCharacters.random() + } + val encodedLongUrl = "${tinyUrl}${fakeHashCode}" + encodeMap[longUrl] = encodedLongUrl + decodeMap[encodedLongUrl] = longUrl + return encodedLongUrl + } + + // Decodes a shortened URL to its original URL. + fun decode(shortUrl: String): String { + //since we are guaranteed that the shortUrl has been encoded + return decodeMap[shortUrl]!! + } +} + +/** + * Your Codec object will be instantiated and called as such: + * var obj = Codec() + * var url = obj.encode(longUrl) + * var ans = obj.decode(url) + */