Java Solution from GeeksforGeeks


  • 1

    This solution is based on the idea from an article on GeeksforGeeks.

    There is an index for every URL in the database. The algorithm encodes the index to a short string and then decodes it to get the index to retrieve the original URL in the database.

    public class Codec {
        private HashMap<Long, String> db = null;
        private long id = 0;
        private char[] dict = null;
        private int BASE = 0;
    
        public Codec() {
            db = new HashMap<>();
            dict = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
     'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 
    'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
            BASE = dict.length;
        }
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            long index = insertUrl(longUrl);
            StringBuilder sb = new StringBuilder();
            while (index > 0) {
                sb.insert(0, dict[(int) (index % BASE)]);
                index /= BASE;
            }
            return sb.toString();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            long index = 0;
            for (char c : shortUrl.toCharArray()) {
                if ('a' <= c && c <= 'z')
                    index = index * 62 + c - 'a';
                if ('A' <= c && c <= 'Z')
                    index = index * 62 + c - 'A' + 26;
                if ('0' <= c && c <= '9')
                    index = index * 62 + c - '0' + 52;
            }
    
            return readUrl(index);
        }
    
        private String readUrl(long index) {
            if (db.containsKey(index))
                return db.get(index);
            return "";
        }
    
        private long insertUrl(String longUrl) {
            id++;
            db.put(id, longUrl);
            return id;
        }
    }
    

Log in to reply
 

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