tinyUrl

作者: Mervyn_2014 | 来源:发表于2017-11-30 14:00 被阅读24次
public static void main(String[] args) {
       String url =  "https://leetcode.com/problems/encode-and-decode-tinyurl/discuss/";
        String encode = encode(url);
        String decode = decode(encode);
        System.out.println(url);
        System.out.println(encode);
        System.out.println(decode);
    }
    static Map<String,String> map = new HashMap<>();
    static String base = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    // Encodes a URL to a shortened URL.
    public static String encode(String longUrl) {
        Integer i = longUrl.hashCode();
        map.put(base10ToBase62(i.longValue()),longUrl);
        return "http://tinyurl.com/"+base10ToBase62(i.longValue());
    }

    // Decodes a shortened URL to its original URL.
    public static String decode(String shortUrl) {
        String s = map.get(shortUrl.replaceAll("http://tinyurl.com/",""));
        return s;
    }
    public static String base10ToBase62(Long n) {
        StringBuilder sb = new StringBuilder();
        while (n != 0) {
            Long l = n % 62;
            sb.insert(0,base.charAt(l.intValue()));
            n /= 62;
        }
        return sb.toString();
    }
    public static Long base62ToBase10(String str) {
        Long n = 0l;
        for (int i = 0; i < str.length(); i++) {
            n=n*62+base.indexOf(str.charAt(i));
        }
        return n;
    }
    public int convert(char c) {
        if (c >= '0' && c <= '9')
            return c - '0';
        if (c >= 'a' && c <= 'z') {
            return c - 'a' + 10;
        }
        if (c >= 'A' && c <= 'Z') {
            return c - 'A' + 36;
        }
        return -1;
    }

相关文章

网友评论

      本文标题:tinyUrl

      本文链接:https://www.haomeiwen.com/subject/jdsvbxtx.html