首页 > Web开发 > 详细

[LC] 535. Encode and Decode TinyURL

时间:2020-04-27 12:15:10      阅读:68      评论:0      收藏:0      [点我收藏+]

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.

 

public class Codec {
    Map<String, String> map = new HashMap<>();
    String charSet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    // Encodes a URL to a shortened URL.
    public String encode(String longUrl) {
        Random rand = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = rand.nextInt(charSet.length());
            sb.append(charSet.charAt(index));
        }
        String url = "http://tinyurl.com/" + sb.toString();
        if (!map.containsKey(url)) {
            map.put(url, longUrl);
        }
        return url;
    }

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

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

 

[LC] 535. Encode and Decode TinyURL

原文:https://www.cnblogs.com/xuanlu/p/12785612.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!