535. Encode and Decode TinyURL - Medium

前往題目

想法

  • 直接產出隨機字串,然後把longUrlcode做連結

思路

encode:

  1. 檢查是否該longUrl已經在資料庫,有的話回傳對應的code
  2. 沒有的話產生一個code,並且檢查是否有重複的,有的話重新生成
  3. 存到map

decode:

  1. 回傳對應的longUrl

Code

public class Codec {
    // shortUrl -> long
    Map<String, String> codeDb = new HashMap<>();
    // longUrl -> short
    Map<String, String> urlDb = new HashMap<>();
    static final String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    // Generate code
    private String generateCode() {
        char[] code = new char[6];
        for (int i = 0; i < 6; ++i) {
            code[i] = chars.charAt((int)(Math.random() * 62));
        }
        return "http://tinyurl.com/" + String.valueOf(code);
    }

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        // Check if already in db
        if (urlDb.containsKey(longUrl)) return urlDb.get(longUrl);
        String code = generateCode();
        // In case duplicate code appears
        while (codeDb.containsKey(code)) code = generateCode();

        // Store to db
        codeDb.put(code, longUrl);
        urlDb.put(longUrl, code);
        return code;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return codeDb.get(shortUrl);
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

535. Encode and Decode TinyURL - Medium
https://f88083.github.io/2024/03/29/535-Encode-and-Decode-TinyURL-Medium/
作者
Simon Lai
發布於
2024年3月29日
許可協議