Leetcode 535: Encode and Decode TinyURL

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 535: Encode and Decode 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.

 

 1 public class Codec {
 2     private const string pref = "http://tinyurl.com/";
 3     
 4     // in thoery should use a hash founction
 5     private int counter = 0;
 6     private Dictionary<int, string> hashToUrl = new Dictionary<int, string>();
 7     private Dictionary<string, int> urlToHash = new Dictionary<string, int>();
 8     
 9     // Encodes a URL to a shortened URL
10     public string encode(string longUrl) {
11         if (!urlToHash.ContainsKey(longUrl))
12         {
13             urlToHash[longUrl] = counter;
14             hashToUrl[counter] = longUrl;
15             counter++;    
16         }
17         
18         return pref + urlToHash[longUrl];
19     }
20 
21     // Decodes a shortened URL to its original URL.
22     public string decode(string shortUrl) {
23         int hash = Int32.Parse(shortUrl.Substring(19, shortUrl.Length - 19));
24         
25         return hashToUrl[hash];
26     }
27 }
28 
29 // Your Codec object will be instantiated and called as such:
30 // Codec codec = new Codec();
31 // codec.decode(codec.encode(url));

 

以上是关于Leetcode 535: Encode and Decode TinyURL的主要内容,如果未能解决你的问题,请参考以下文章

leetcode535 - Encode and Decode TinyURL - medium

535. Encode and Decode TinyURL - LeetCode

[LeetCode] 535. Encode and Decode TinyURL 编码和解码短URL

535. Encode and Decode TinyURL

535. Encode and Decode TinyURL

535. Encode and Decode TinyURL