设计 tinyURL

设计 TinyURL

设计一个 TinyURL 服务,当输入 https://leetcode.com/problems/design-tinyurl 时,返回 http://tinyurl.com/4e9iAk

基础想法,a-zA-Z0-9 有 62 个字符,所以可以随机生成一个长度为 6 位的字符串。只要重复了,就一直不停的循坏调用直到生成一个不重复的。

import java.util.concurrent.ThreadLocalRandom;

class Codec
{
    static final Map<String, String> shortToLongMap = new HashMap<String, String>();
    static final Map<String, String> LongToShortMap = new HashMap<String, String>();
    static final String BASE_HOST = "http://tinyurl.com/";
    static final int K = 6;
    
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl)
	{
        if(LongToShortMap.containsKey(longUrl))
			return LongToShortMap.get(longUrl);

        String shortUrl = generateRandomShortUrl();
        
        while(shortToLongMap.containsKey(shortUrl));
            shortUrl = generateRandomShortUrl();

		shortToLongMap.put(shortUrl, longUrl);
        LongToShortMap.put(longUrl, shortUrl);
        return shortUrl;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl)
	{
        return shortToLongMap.get(shortUrl);
    }
    
    private String generateRandomShortUrl()
    {
        final String BASE62 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder();
        
        for (int i = 0; i < K; i++)
        {
            int randomIndex = ThreadLocalRandom.current().nextInt(0, BASE62.length());
            sb.append(BASE62.charAt(randomIndex));
        }
        String shortUrl = BASE_HOST + sb.toString();
        return shortUrl;
    }
}

参考