Leetcode Encode and Decode tinyurl
First put the title:
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.
Obviously the title means to encode a longer url into a shorter URL and then restore it to a shorter URL by decoding it. Examples of topics are:
https://leetcode.com/problems/design-tinyurl-encoding-http://tinyurl.com/4e9iak
http://tinyurl.com/4e9iak– decoding-https://leetcode.com/problems/design-tinyurl
There are no restrictions on the coding and decoding algorithms in the requirements, so there are more solutions. The first idea takes the list collection, where the encoding process is to put the original URL into the collection and then return its subscript in the list collection (which needs to be converted to a string type), and the decoding process is to pass in the subscript returned by the URL (which needs to be converted to the int type). The original URL in the list is then removed by subscript. The specific code is as follows:
public static string encode (string longurl) {
urls.add (longurl);
Return string.valueof (Urls.size ()-1);
}
public static string decode (String shorturl) {
int index = integer.valueof (shorturl);
Return Urls.get (index);
}
The second idea is to use the HashMap to place the size and the original URL into a map to form a key-value pair. Decoding the value according to the key, you can get the original URL. The specific implementation code is as follows:
public class Codec {
private static map<string,string> HashMap = new hashmap<string,string> ();
Encodes a URL to a shortened URL.
public string Encode (string longurl) {
hashmap.put (string.valueof (Hashmap.size () +1), longurl);
Return string.valueof (Hashmap.size ());
}
Decodes a shortened URL to its original URL.
public string decode (string shorturl) {
return hashmap.get (Shorturl);
}
}