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.
TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk.
要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法。你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/encode-and-decode-tinyurl
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
TinyURL 的加密与解密。
题意没什么可解释的,说一下思路。需要创建一个mapping,里面包含大小写字母和十个数字一共26 + 26 + 10 = 62个digit可供选择。由于encode的时候,最后生成的短的URL只需要有6位即可,因为6位可以产生6 ^ 62种组合,超过了全网所有的长URL的总和,所以足够用了。用一个random函数生成每一位上的随机的数字/字母,把所有生成的char append成一个字符串,最后将(shortURL, longURL)放入hashmap。
解码的时候只是带着shortURL去hashmap里看是否有这个key。
Encode
时间O(n)
空间O(n)
Decode
时间O(1)
Java实现
1 public class Codec { 2 String mapping = "abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789"; 3 HashMap<String, String> map = new HashMap<>(); 4 // Encodes a URL to a shortened URL. 5 public String encode(String longUrl) { 6 Random random = new Random(); 7 StringBuilder res = new StringBuilder(); 8 for (int i = 0; i < 6; i++) { 9 int index = random.nextInt(mapping.length()); 10 res.append(mapping.charAt(index)); 11 } 12 if (!map.containsKey(res)) { 13 map.put(res.toString(), longUrl); 14 } 15 return res.toString(); 16 } 17 18 // Decodes a shortened URL to its original URL. 19 public String decode(String shortUrl) { 20 return map.get(shortUrl); 21 } 22 } 23 24 // Your Codec object will be instantiated and called as such: 25 // Codec codec = new Codec(); 26 // codec.decode(codec.encode(url));