码迷,mamicode.com
首页 > Web开发 > 详细

LeetCode - Encode and Decode TinyURL

时间:2018-09-27 13:10:00      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:methods   ash   algorithm   iat   code   tco   hashmap   block   rest   

Note: This is a companion problem to the System Design problem: Design TinyURL.

TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk.

Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.

 

这里长网址变成短网址采用的方法是,定义一个常量字符串0-9a-zA-Z,每次将长网址作为key存入Map时,在将对应的短网址(在那个字符串常量中随机挑去6个作为短网址)作为对应的value存入map中,在将两者对换,存入另一个map中,用于将短网址变成长网址。存入过程中会判断长网址是否出现过,以及随机生成的短网址是否出现过,在做相应处理。

public class Codec {
    private static final String dict = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIKKLMNOPQRSTUVWXYZ";
    Map<String,String> longToShort = new HashMap<>();
    Map<String,String> shortToLong = new HashMap<>();
    
    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        if(longToShort.containsKey(longUrl)){
            return longToShort.get(longUrl);
        }
        String encoded =  encodeString();
        while(shortToLong.containsKey(encoded)){
            encoded = encodeString();
        }
        longToShort.put(longUrl, encoded);
        shortToLong.put(encoded, longUrl);
        return encoded;
    }
    
    public String encodeString(){
        String res = "";
        for(int i = 0; i<6; i++){
            String str = String.valueOf(dict.charAt((int)(Math.random()*62)));
            res = res + str;
        }
        return res;
    }

    // Decodes a shortened URL to its original URL.
    public String decode(String shortUrl) {
        if(shortToLong.containsKey(shortUrl)){
            return shortToLong.get(shortUrl);
        }
        return "";
    }
}

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

 

LeetCode - Encode and Decode TinyURL

标签:methods   ash   algorithm   iat   code   tco   hashmap   block   rest   

原文地址:https://www.cnblogs.com/incrediblechangshuo/p/9712302.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!