例题:
https://leetcode.cn/problems/encode-and-decode-tinyurl/description/
分析:
题目要求可以将一个长网址变成一个短网址(encode),也可以通过短网址找到原来的长网址,我们可以使用两个hashMap集合来实现。 longToShort 和 shortToLong 两个集合。longToShort集合 的key为 长网址, value为生成的短网址, 同时往shortToLong集合中加入key为短网址,value为原来的长网址。
代码实现:
static class CodecHashCode {private static final String PREFIX_URL = "http://tinyurl.com/";private static final Map<String,String> longToShort = new HashMap<>();private static final Map<String,String> shortToLong = new HashMap<>();// Encodes a URL to a shortened URL.public String encode(String longUrl) {String shortUrl = longToShort.get(longUrl);if(shortUrl != null){return shortUrl;}//当encode方法被调用多次后,生成的id可能相同,也就是短网址可能相同,需要先判断一下int id = longUrl.hashCode();while(true){shortUrl = PREFIX_URL + id;if(!shortToLong.containsKey(shortUrl)){longToShort.put(longUrl, shortUrl);shortToLong.put(shortUrl, longUrl);break;}id++;}return longToShort.get(longUrl);}// Decodes a shortened URL to its original URL.public String decode(String shortUrl) {return shortToLong.get(shortUrl);}}
上一种方法要考虑生成的短网址冲突问题, 为了简化判断,可以用递增数来实现
private static int id = 1;// Encodes a URL to a shortened URL.public String encode(String longUrl) {String shortUrl = longToShort.get(longUrl);if(shortUrl != null){return shortUrl;}shortUrl = PREFIX_URL + id;longToShort.put(longUrl, shortUrl);shortToLong.put(shortUrl, longUrl);id++;return longToShort.get(longUrl);}