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 Retu RNs A short URL such as Http://tinyurl.com/4e9iAk.
Design the Encode and decode methods for the TinyURL service. There is no restriction on what your encode/decode algorithm should work. You just need to ensure, that a URL can is encoded to a tiny URL and the tiny URL can is decoded to the original URL.
Think of the possible repeated coding problem, directly with HashMap made a short URL and a long URL mapping. Mix numbers and letters to encode, according to the title of the 6-digit encoding words can achieve \ (36^6\) encoding, theoretical performance is OK.
The code is as follows
Public classCodec {hashmap<string, string> Enindex =NewHashmap<string, string> (); Hashmap<string,string>deindex =NewHashmap<string, string> (); String keyset ="0123456789abcdefghijklmnopqrstuvwyz"; String tinyurlbase ="http://tinyurl.com/";//Encodes a URL to a shortened URL. PublicStringencode(String Longurl) {String key;if(Enindex.ContainsKey(Longurl))returnEnindex.Get(Longurl); Do{StringBuilder SB =NewStringBuilder (); for(inti =0; i<6; i++) {sb.Append(Keyset.charAt((int) (Math.Random() *keyset.length()))); } key = sb.toString(); } while(Deindex.ContainsKey(key)); Deindex.put(Key,longurl); Enindex.put(Longurl, Tinyurlbase+key);returnTinyurlbase+key; }//Decodes a shortened URL to its original URL. PublicStringDecode(String Shorturl) {returnDeindex.Get(Shorturl.Replace(Tinyurlbase,"")); }}
After finishing reading the next ranking ..... Looks pretty low. But the feeling is relatively free, should not be too much time, the feeling is to consider how to encode better.
The preceding scenarios are broadly:
- Encode with counter
Then the current server how many URLs are exposed to exposure, there may be security implications. And the other disadvantage of the counter code is that the numbers will grow.
- Return parameters directly (fastest)
.... The OJ of this problem is basically the same, the two functions directly return the parameter string can also pass OJ, embarrassed
Encode and Decode TinyURL