题解 | #某度短网址#

某度短网址

http://www.nowcoder.com/practice/4aee5c3a31be4b3a9fe0181778ded0ab

其实题目给的挺清晰地了 按照规则一步步搞就行,这里用了一个shortMap存放短网址对应的长网址用来节省计算

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * @param long_url  string字符串ArrayList
     * @param short_url string字符串ArrayList
     * @return string字符串ArrayList
     */
    char[] keyChar = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    Map<Long,String> keyMap = new HashMap<>();
    Map<String, String> shotMap = new HashMap<>();
    public ArrayList<String> urlTransformation(ArrayList<String> long_url, ArrayList<String> short_url) {
        // write code here
        ArrayList<String> result = new ArrayList<>();
        for (String longUrl : long_url) {
            String key = getKey(longUrl);
            shotMap.put(key, longUrl);
            result.add(key);
        }

        for (String shotUrl : short_url) {
            result.add(shotMap.get(shotUrl));
        }

        return result;
    }

    public String getKey(String longUrl) {
        Long key = 0L;

        char[] chars = longUrl.toCharArray();

        for (char aChar : chars) {
            key = (key * 64 + aChar) % 56800235584L;
        }

        while (keyMap.containsKey(key) && !keyMap.get(key).equals(longUrl)) {
            key = (key + 1) % 56800235584L;
        }
        keyMap.put(key,longUrl);


        return makeKey(key);
    }

    public String makeKey(Long key) {

        StringBuilder str = new StringBuilder();
        while (key > 0) {
            str.append(keyChar[(int) (key % 62)]);
            key = key / 62;
        }

        while (str.length() < 6){
            str.append('0');
        }

        return "http://tiny.url" + str.reverse().toString();
    }
}
全部评论

相关推荐

我即大橘:耐泡王
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务