535. Encode and Decode TinyURL
2017-03-16 19:51
549 查看
public class Codec { // Encodes a URL to a shortened URL. private String prefix = "http://tinyurl.com/"; private static Map<String,String> indexMap = new HashMap<String,String>(); private static Map<String,String> reverseMap = new HashMap<String,String>(); private static final String code = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // Encodes a URL to a shortened URL. public String encode(String longUrl) { if(indexMap.containsKey(longUrl)){ return indexMap.get(longUrl); } StringBuffer shortUrl = new StringBuffer(); do{ for(int i=0;i<6;i++){ int n = (int)Math.random()*code.length(); shortUrl.append(code.charAt(n)); } }while(reverseMap.containsKey(shortUrl)); String res = prefix+shortUrl.toString(); reverseMap.put(res, longUrl); indexMap.put(longUrl, res); return res; } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return reverseMap.get(shortUrl); } }
相关文章推荐
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- Leetcode刷题之路(Python)——535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- 【LeetCode】535. Encode and Decode TinyURL
- LeetCode:535. Encode and Decode TinyURL
- Math-535-Encode and Decode TinyURL
- 535 Encode and Decode TinyURL
- python--leetcode 535. Encode and Decode TinyURL
- HashTable-535-Encode and Decode TinyURL
- 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
- 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL
- 535. Encode and Decode TinyURL
- leetcode 535. Encode and Decode TinyURL