您的位置:首页 > 其它

LeetCode 535: Encode and Decode TinyURL

2017-09-03 12:51 441 查看
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));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: