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));

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10212232.html