Leetcode: Encode and Decode TinyURL
Note: This is a companion problem to the System Design problem: Design TinyURL. 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. Subscribe to see which companies asked this question.
1. 根据系统设计的Estimation of the amount of data we need to store for the next couple of years, 我们应需要6位Base62的char来encode
2. assume 避免地址爆炸,相同的longUrl得到相同的shortUrl, 这需要一个额外的hashMap longToShort
3. 这里因为我们想保证都是6位的shortURL,所以采用random generate的方法;其他方法还可以是编号等等
1 public class Codec { 2 HashMap<String, String> hashToUrl = new HashMap<String, String>(); 3 HashMap<String, String> urlToHash = new HashMap<String, String>(); 4 String tinyUrlBase = "http://tinyurl.com/"; 5 String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; 6 Random random = new Random(); 7 8 // Encodes a URL to a shortened URL. 9 public String encode(String longUrl) { 10 if (urlToHash.containsKey(longUrl)) 11 return tinyUrlBase + urlToHash.get(longUrl); 12 13 StringBuilder hash = new StringBuilder(); 14 do { 15 for (int i=0; i<6; i++) { 16 hash.append(characters.charAt(random.nextInt(characters.length()))); 17 } 18 } while (hashToUrl.containsKey(hash.toString())); 19 20 hashToUrl.put(hash.toString(), longUrl); 21 urlToHash.put(longUrl, hash.toString()); 22 return tinyUrlBase + hash.toString(); 23 } 24 25 // Decodes a shortened URL to its original URL. 26 public String decode(String shortUrl) { 27 return hashToUrl.get(shortUrl.substring(tinyUrlBase.length())); 28 } 29 } 30 31 // Your Codec object will be instantiated and called as such: 32 // Codec codec = new Codec(); 33 // codec.decode(codec.encode(url));
分类:
Leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架