Simple Java Base(26+10) Solution


  • 0
    public class Codec {
        
        List<String> mem = new ArrayList<>();
        char[] map = {'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'};
    
        // Encodes a URL to a shortened URL.
        public String encode(String longUrl) {
            int id = mem.size();
            StringBuffer sb = new StringBuffer();
            while(id>0) {
                sb.append(map[id%map.length]);
                id /= 36;
            }
            mem.add(longUrl);
            return sb.toString();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            int id = 0;
            for(int i=shortUrl.length()-1; i>=0; i--) {
                char c = shortUrl.charAt(i);
                if (c>='a' && c<='z')
                    id = id*map.length + c-'a';
                else
                    id = id*map.length + c-'0' + 26;
            }
            return mem.get(id);
        }
    }

Log in to reply
 

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