leetcode535

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

时间: 2024-11-08 21:48:05

leetcode535的相关文章

leetcode-535. TinyURL 的加密与解密

TinyURL是一种URL简化服务, 比如:当你输入一个URL https://leetcode.com/problems/design-tinyurl 时,它将返回一个简化的URL http://tinyurl.com/4e9iAk. 要求:设计一个 TinyURL 的加密 encode 和解密 decode 的方法.你的加密和解密算法如何设计和运作是没有限制的,你只需要保证一个URL可以被加密成一个TinyURL,并且这个TinyURL可以用解密方法恢复成原本的URL. 思路: 首先读懂题意

leetcode535 - Encode and Decode TinyURL - medium

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 rest