Accepted Java Solution Easy to Understand


  • 0
    A
    public class Codec {
    
        // Encodes a URL to a shortened URL.
        Map<String, String> map = new HashMap();
        public String encode(String longUrl) {
            int index = longUrl.indexOf("//");
            String sub = longUrl.substring(index+2);
            int num = 0;
            for(int i=0;i<sub.length();i++) {
                if(Character.isLetter(sub.charAt(i))) {
                    num += (sub.charAt(i)-'a')*(i+1);
                } else if(Character.isDigit(sub.charAt(i))) {
                    num += (sub.charAt(i)-'0')*(i+1);
                } else {
                    num += i+1;
                }
            }
            String result = helper(num+"");
            result = "http://tinyurl.com/" + result;
            System.out.println(result);
            map.put(result, longUrl);
            return result;
        }
        
        public String helper(String num) {
            StringBuilder res = new StringBuilder();
            int i=0;
            Random r = new Random();
            while(i<num.length()) {
                res.append(Character.toString(num.charAt(i)));
                i++;
                if(i<num.length()) {
                    char c = (char)((Character.getNumericValue(num.charAt(i))*r.nextInt(27) % 26) +'A');
                    res.append(Character.toString(c)) ;
                }
                i++;
                if(i<num.length()) {
                    char c = (char)((Character.getNumericValue(num.charAt(i))*r.nextInt(27) % 26) +'a');
                    res.append(Character.toString(c)) ;
                }
                i++;
            }
            return res.toString();
        }
    
        // Decodes a shortened URL to its original URL.
        public String decode(String shortUrl) {
            return map.get(shortUrl);
        }
    }

Log in to reply
 

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