1. 程式人生 > >535. Encode and Decode TinyURL - Medium

535. Encode and Decode TinyURL - Medium

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.

 

用兩個hash map,分別表示long to short (map1) 和 short to long (map2) ,並把要用到的大小寫字母和數字用string表示出來待用

encode: 先check map1中是否有longURL, 如果存在直接返回對應的shortURL;如果沒有,在string中隨機選n個字元組合,並檢查map2中是否存在該組合,如果存在再增加n個字元,直到該url組合是unique的。然後分別在map1, map2中都存入這對url pair

decode: 直接返回map2中對應long url即可

public class Codec {
    HashMap<String, String> long2short = new HashMap<>();
    HashMap<String, String> short2long = new
HashMap<>(); String ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; Random r = new Random(); // Encodes a URL to a shortened URL. public String encode(String longUrl) { if(long2short.containsKey(longUrl)) { return "http://tinyurl.com/" + long2short.get(longUrl); } StringBuilder sb = new StringBuilder(); while(short2long.containsKey(sb.toString())) { for(int i = 0; i < 6; i++) { sb.append(ch.charAt(r.nextInt(ch.length()))); } } long2short.put(longUrl, sb.toString()); short2long.put(sb.toString(), longUrl); return "http://tinyurl.com/" + sb.toString(); } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { return short2long.get(shortUrl.substring("http://tinyurl.com/".length())); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));