Kotlin Leetcode - 535. Encode and Decode TinyURL
class Codec() {
fun encode(longUrl: String): String {
}
fun decode(shortUrl: String): String {
}
}
/**
* Your Codec object will be instantiated and called as such:
* var obj = Codec()
* var url = obj.encode(longUrl)
* var ans = obj.decode(url)
*/
解題思路
這一題考的主要是對字串的處理
我們可以建立一個 mutableMapOf<String, String>()
來儲存短網址和長網址的關聯
Kotlin 參考解答
class Codec() {
private val map = mutableMapOf<String, String>()
fun encode(longUrl: String): String {
val key = Integer.toHexString(longUrl.hashCode())
map[key] = longUrl
return "http://tinyurl.com/$key"
}
fun decode(shortUrl: String): String {
val key = shortUrl.substring(shortUrl.indexOfLast { it == '/' } + 1)
return map[key]!!
}
}
回到 leetcode 列表