码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode535

时间:2017-04-28 16:06:46      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:second   targe   dict   origin   original   UI   ant   href   problems   

public class Codec
    {
        const string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

        Dictionary<string, string> url2code = new Dictionary<string, string>();
        Dictionary<string, string> code2url = new Dictionary<string, string>();

        const string TINYURL = "http://tinyurl.com/";

        // Encodes a URL to a shortened URL
        public string encode(string longUrl)
        {
            while (!url2code.ContainsKey(longUrl))//原来没有这个url的short版本
            {
                //需要生成一个新的
                var random = new Random(DateTime.Now.Millisecond);
                StringBuilder sb = new StringBuilder();
                while (sb.Length < 6)
                {
                    var index = random.Next(62);
                    sb.Append(alphabet[index]);
                }
                var code = TINYURL + sb.ToString();
                if (!code2url.ContainsKey(code))//新生成的这个code,之前没用过
                {
                    url2code.Add(longUrl, code);
                    code2url.Add(code, longUrl);
                }
            }
            return url2code[longUrl];
        }

        // Decodes a shortened URL to its original URL.
        public string decode(string shortUrl)
        {
            if (code2url.ContainsKey(shortUrl))
            {
                return code2url[shortUrl];
            }
            else
            {
                return shortUrl;
            }
        }
    }

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

https://leetcode.com/problems/encode-and-decode-tinyurl/#/description

leetcode535

标签:second   targe   dict   origin   original   UI   ant   href   problems   

原文地址:http://www.cnblogs.com/asenyang/p/6781471.html

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