Accepted Java Solution


  • 0
    J
    public class Codec {
    
        private final int LEN = 6;
        private final String charset = "abcdefghijklmnopqrsturwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        
        private Map<String, String> url_to_tiny = new HashMap<String, String>();
        private Map<String, String> tiny_to_url = new HashMap<String, String>();
        
        int[] idy = new int[LEN];
        
        public Codec() {
            for (int i=0; i<idy.length; i++) {
                idy[i] = 0;
            }
            idy[idy.length-1] = -1;
        }
        
        /**
         * generate a string based on idy values
         * @return
         */
        public String generateTiny() {
            StringBuilder result = new StringBuilder();
            for (int i : idy) {
                result.append(charset.charAt(i));
            }
            
            return result.toString();
        }
     
        /**
         * adjust idy values (recursively)
         * @param i   index to adjust
         * @return
         */
        private boolean adjust(int i) {
    
            idy[i]++;
            if (idy[i] >= charset.length() && i == 0)
                return false;
            if (idy[i] >= charset.length())  {
                idy[i] = 0;
                return adjust(i-1);
            }
            return true;
        }
        
        /**
         * decode tiny url to its real form
         * @param tiny
         * @return
         */
        public String decode(String tiny) {
            if (tiny.isEmpty()) return "";
            return tiny_to_url.get(tiny);
        }
        
        /**
         * encode url to its tiny form
         * @param url
         * @return
         */
        public String encode(String url) {
            if (url.isEmpty())
                return "";
            String tiny = url_to_tiny.get(url);
            if (tiny == null) {
                if (adjust(LEN-1)) {
                    tiny = generateTiny();
                    url_to_tiny.put(url, tiny);
                    tiny_to_url.put(tiny, url);
                } 
            }
            return tiny;
        }
    }
    
    

  • 0
    J

    @Jeff.Jing

    idy is an array to keep track of indice of each character of tiny url in charset. My key (between 'z' and 'c') doesn't work.


Log in to reply
 

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