Encode and Decode TinyURL

时间:2024-01-07 19:42:38

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.

解法来自:https://leetcode.com/problems/encode-and-decode-tinyurl/discuss/100270/Three-different-approaches-in-java

Approach 1- Using simple counter

 public class Codec {
Map<Integer, String> map = new HashMap<>();
int i=;
public String encode(String longUrl) {
map.put(i,longUrl);
return "http://tinyurl.com/"+i++;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}

Approach 2- using hashcode


 public class Codec {
Map<Integer, String> map = new HashMap<>();
public String encode(String longUrl) {
map.put(longUrl.hashCode(),longUrl);
return "http://tinyurl.com/"+longUrl.hashCode();
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}

Approach 3- using random function

 public class Codec {
Map<Integer, String> map = new HashMap<>();
Random r=new Random();
int key=r.nextInt();
public String encode(String longUrl) {
while(map.containsKey(key)) {
key= r.nextInt();
}
map.put(key,longUrl);
return "http://tinyurl.com/"+key;
}
public String decode(String shortUrl) {
return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", "")));
}
}