535. Encode and Decode TinyURL
535. Encode and Decode TinyURL 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-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. https://leetcode.com/problems/encode-and-decode-tinyurl/solution/ Simply put, hashCode() returns an integer value, generated by a hashing algorithm. // accepted public class Codec { // example of a long url : // https://www.google.com/search?q=long+url&num=100&rlz=1C5CHFA_enUS766US767&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj4vMD-yazeAhWDAHwKHdlOCuwQ_AUIDigB&biw=1343&bih=734 // hashed = hashcode(long url) = 4e9iAk // example of a short url : // "http://tinyurl.com/4e9iAk" // map < key : hashedcode , value : long url > // process : we get a long url, we get the hashcode of this long url, we store the hashed result and the long url to the // map, // return http://tinyurl.com/ + hashed result // for decoding : // we have the short url, we get the hashsed result part, and then we return the long url from the map Map<Integer, String> map = new HashMap<>(); // Encodes a URL to a shortened URL. public String encode(String longUrl) { Integer hashResult = longUrl.hashCode(); map.put(hashResult, longUrl); return "http://tinyurl.com/" + hashResult; // string concatenation with an integer ? yes } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { // Integer.valueOf() Integer hashResult = Integer.valueOf(shortUrl.replace("http://tinyurl.com/", "")); // .replace( , ) return map.get(hashResult); } }
posted on 2018-11-08 17:04 猪猪🐷 阅读(164) 评论(0) 收藏 举报
浙公网安备 33010602011771号