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));