本文主要是介绍Encode and Decode 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.
题目要求把一个url进行编码解码,具体怎么编码没关系,我们只要能编一个就行,那么很容易想到用hashCode
这个方法,它可以根据对象生成一个整数序列,那么我们可以将hashcode作为key存储在一个容器里,然后url作为value。那么encode就是put的操作,decode则是get的操作。
实现:
public class EncodeAndDecodeTinyURL {private static HashMap cache = new HashMap();// Encodes a URL to a shortened URL.public static String encode(String longUrl) {cache.put(longUrl.hashCode(), longUrl);return String.valueOf(longUrl.hashCode());}// Decodes a shortened URL to its original URL.public static String decode(String shortUrl) {return cache.get(Integer.valueOf(shortUrl)).toString();}public static void main(String[] args) {System.out.println(encode("https://leetcode.com/problems/design-tinyurl"));System.out.println(decode(encode("https://leetcode.com/problems/design-tinyurl")));}
}
这篇关于Encode and Decode TinyURL的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!