We need to record the relationship between the long URL and the short URL and vice versa.
class Codec() {
private val long2Short = HashMap<String, String>()
private val short2Long = HashMap<String, String>()
private val chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
private val shortUrlLength = 6
// Encodes a URL to a shortened URL.
fun encode(longUrl: String): String {
if (longUrl in long2Short) return long2Short[longUrl]!!
var shortUrl: String
do {
shortUrl = generateShortUrl(longUrl)
} while (shortUrl in short2Long)
long2Short[longUrl] = shortUrl
short2Long[shortUrl] = longUrl
return shortUrl
}
// Decodes a shortened URL to its original URL.
fun decode(shortUrl: String): String {
return short2Long[shortUrl] ?: ""
}
private fun generateShortUrl(longUrl: String): String {
val url = StringBuilder()
repeat(shortUrlLength) {
val index = (Math.random() * chars.length).toInt()
url.append(chars[index])
}
return url.toString()
}
}