Java solution uses maps to store increasing id and its base62


  • 0
    D
    private long mId = 0;
    private static String HOST_NAME = "http://tinyurl.com/";
    private HashMap<String, Long> mLongUrlToId = new HashMap<>();
    private HashMap<Long, String> mIdToLongUrl = new HashMap<>();
    private HashMap<String, Long> mShortUrlToId = new HashMap<>();
    private String s= "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        if (mLongUrlToId.containsKey(longUrl)) {
            long id = mLongUrlToId.get(longUrl);
            return convertToBase62(id);
        }
        mLongUrlToId.put(longUrl, mId);
        mIdToLongUrl.put(mId, longUrl);
        String shorten = convertToBase62(mId);
        mShortUrlToId.put(shorten, mId);
        mId++;
        return shorten;
    }
    
    private String convertToBase62(long id) {
        StringBuilder sb = new StringBuilder();
        sb.append(HOST_NAME);
        while(id > 0) {
            long r= id % 62;
            id /= 62;
            sb.insert(0, s.charAt((int)r));
        }
        return sb.toString();
    }
    
    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        long id = mShortUrlToId.get(shortUrl);
        return mIdToLongUrl.get(id);
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.