leetcode535.Encode and Decode TinyURL

Read this in "about 1 minute".

Encode and Decode TinyURL
This is a String handler problem.

Problem

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.

Solution

To build a rule for transformation, I suppose it should take numbers or something else as a key, then the long url is the value. By this way, short url containing key can be used to find original long url.

Solution 1: to use random key for storage like GUID,MD5 or TimeStamp.
Solution 2: to use hashCode() in Java.
hashCode()is a method for quick finding and searching. If two objects are equals(), then their hashCode are the same. While if two objects’ hashCodes are the same, they may not be equal. So the solution may make accidents.
So the sample solution is here using hashCode():

public class Main
{
public static Map<Integer,String> map
  =new HashMap<Integer,String>();
public static String host = “http://tinyurl.com/”;
public static String EnCode(String initial)
 {
  int key=initial.hashCode();
  map.put(key,initial);
  return host+key;
  }
public static String DeCode(String url)
 {
  int key=Integer.parseInt(url.replace(host,””));
  String value=map.get(key);
  return value;
  }
}

REFERENCE LINK : LeetCode


Quote Day
Getting up is half success to a day.

Author

Typing Theme

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora non aut eos voluptas debitis unde impedit aliquid ipsa.

 The comment for this post is disabled.