535. Encode and Decode TinyURL
package LeetCode_535 /** * 535. Encode and Decode TinyURL * https://leetcode.com/problems/encode-and-decode-tinyurl/description/ * * TinyURL is a URL shortening service where you enter a URL such as * https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. * */ class Codec() { /* * solution, Two HaspMap * */ private val BASE_URL = "http://tinyurl.com/" //total 62 characters for generate short_url val chatSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" //key is long url,value short url val mapShortUrl = HashMap<String, String>() //key is short url,value long url val mapLongUrl = HashMap<String, String>() // Encodes a URL to a shortened URL. fun encode(longUrl: String): String { if (mapShortUrl.containsKey(longUrl)) { return mapShortUrl.get(longUrl) ?: "" } var key = "" do { val sb = StringBuilder() for (i in 0..6) { val r = (Math.random() * chatSet.length).toInt() sb.append(chatSet[r]) } key = sb.toString() //if contains key, keep doing generate } while (mapShortUrl.containsKey(longUrl)) val url = BASE_URL + key mapShortUrl.put(longUrl, url) mapLongUrl.put(url, longUrl) return url } // Decodes a shortened URL to its original URL. fun decode(shortUrl: String): String { return mapLongUrl.getOrDefault(shortUrl, "") } } /** * Your Codec object will be instantiated and called as such: * var obj = Codec() * var url = obj.encode(longUrl) * var ans = obj.decode(url) */
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)