public class Codec {
    private long id;
    private Map<Long, String> urlMap;
    private final String elements = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    public Codec() {
        id = 0L;
        urlMap = new HashMap<>();
    }
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        urlMap.put(id, longUrl);
        return encode(id++);
    }
    
    private String encode(long id) {
        StringBuilder result = new StringBuilder();
        while (id > 0) {
            result.append(elements.charAt((int)(id % 62)));
            id /= 62;
        }
        return result.toString();
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        return urlMap.get(mapTo(shortUrl));
    }
    
    private long mapTo(String url) {
        long result = 0;
        for (int i = url.length() - 1; i >= 0; i--) {
            result += maps(url.charAt(i)) * Math.pow(62, (url.length() - i - 1));
        }
        return result;
    }
    
    private int maps(char c) {
        if (c >= '0' && c <= '9') {
            return Integer.valueOf(c);
        } else if (c >= 'a' && c <= 'z') {
            return 10 + (int)(c - 'a');
        } else if ( c >= 'A' && c <= 'Z') {
            return 36 + (int)(c - 'A');
        }
        return 0;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.decode(codec.encode(url));

 

posted on 2017-09-03 12:51  keepshuatishuati  阅读(96)  评论(0编辑  收藏  举报