Encode and Decode TinyURL
2017-03-22 07:12
344 查看
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-tinyurland it returns a short URL such as
http://tinyurl.com/4e9iAk.
Design the
encodeand
decodemethods 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.
Solution: Have two maps: one for encode, another for decode. When encode the URL, be aware of whether the shorterURL has been used. If so, invoke the encode process again. When decode the URL, be aware of whether the shorterURL exists in the decode map. If not, return a null object.
1 public class Codec { 2 private HashMap<String, String> encodeMap = new HashMap<String, String>(); 3 private HashMap<String, String> decodeMap = new HashMap<String, String>(); 4 5 // Encodes a URL to a shortened URL. 6 public String encode(String longURL) { 7 if (encodeMap.containsKey(longURL)) return encodeMap.get(longURL); 8 String newURL = getNextCode(); 9 10 encodeMap.put(longURL, newURL); 11 decodeMap.put(newURL, longURL); 12 13 return newURL; 14 } 15 16 // Decodes a shortened URL to its original URL. 17 public String decode(String shortURL) { 18 if (decodeMap.containsKey(shortURL)) return decodeMap.get(shortURL); 19 else return null; 20 } 21 22 private String getNextCode() { 23 String base = "http://tinyurl.com/"; 24 String dictionary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz"; 25 int subLength = 6, index = 0, n = dictionary.length(); 26 String extension = new String(); 27 while (index++ < 6) { 28 Random rand = new Random(); 29 extension += dictionary.charAt(rand.nextInt(n)); 30 } 31 String newURL = base + extension; 32 33 if (decodeMap.containsKey(newURL)) return getNextCode(); 34 else return newURL; 35 } 36 } 37 38 // Your Codec object will be instantiated and called as such: 39 // Codec codec = new Codec(); 40 // codec.decode(codec.encode(url));
相关文章推荐
- lintcode/leetcode由易至难第21题:Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- Encode and Decode TinyURL
- Encode and Decode TinyURL
- 笔试题12. LeetCode OJ (12) Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- Encode and Decode TinyURL
- LeetCode:535. Encode and Decode TinyURL
- Math-535-Encode and Decode TinyURL
- LeetCode 535: Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- Leetcode 535 Encode and Decode TinyURL
- Encode and Decode TinyURL
- 535 Encode and Decode TinyURL
- Leetcode刷题之路(Python)——535. Encode and Decode TinyURL
- HashTable-535-Encode and Decode TinyURL
- 535. Encode and Decode TinyURL