Question:
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.
Tips:
将长的url转换为短url 将短url转换为长的url。长url与短url之间有一个映射,保证一致。
如输入https://leetcode.com/problems/design-tinyurl 编码之后返回http://tinyurl.com/4e9iAk输入http://tinyurl.com/4e9iAk,decode之后也要返回https://leetcode.com/problems/design-tinyurl。编码方式没有限制,主要是code与decode之后 结果要相同。
思路:
code:
输入类似:https://leetcode.com/problems/design-tinyurl
用longUrl的哈希值作为hashmap的key,longUrl作为value,组成键值对,保存在map中。
返回"http://tinyurl.com/"+longUrl的哈希值,即键值。
decode:
输入类似:http://tinyurl.com/4e9iAk
根据http://tinyurl.com/ 后面的4e9iAk作为key 来查找对应的value就是longUrl
代码:(使用hashmap)
package medium;import java.util.HashMap;import java.util.Map;public class L535EncodeAndDecodeTinyURL { //即将长的url转换为短url 将短url转换为长的url。 //长url与短url之间有一个映射,保证一致。 //如输入https://leetcode.com/problems/design-tinyurl 编码之后返回http://tinyurl.com/4e9iAk //输入http://tinyurl.com/4e9iAk,decode之后也要返回https://leetcode.com/problems/design-tinyurl Mapmap = new HashMap<>(); // Encodes a URL to a shortened URL. public String encode(String longUrl) { map.put(longUrl.hashCode(), longUrl); //System.out.println("long hashCode"+longUrl.hashCode()); return "http://tinyurl.com/" + longUrl.hashCode(); } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); } // Your Codec object will be instantiated and called as such: public static void main(String[] args) { L535EncodeAndDecodeTinyURL l535 = new L535EncodeAndDecodeTinyURL(); System.out.println(l535.decode(l535.encode("https://leetcode.com/problems/design-tinyurl"))); }}