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

Leetcode 535: Encode and Decode TinyURL

时间:2018-01-02 11:38:03      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:pos   https   post   nal   for   color   obj   url   ring   

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

标签:pos   https   post   nal   for   color   obj   url   ring   

原文地址:https://www.cnblogs.com/liangmou/p/8175547.html

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