535. Encode and Decode TinyURLjava
题目大意:实现长连接加密成短连接,短连接解密成长连接app
思路:加密成短连接+key,将长连接按key保存到map,解密时根据短连接提取key,再从map中返回长连接dom
Java实现:加密
public class Codec { // https://leetcode.com/problems/design-tinyurl --> http://tinyurl.com/4e9iAk Map<Integer, String> map = new HashMap<>(); int i = 0; // Encodes a URL to a shortened URL. public String encode(String longUrl) { map.put(i, longUrl); return "http://tinyurl.com/" + (i++); } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { int key = Integer.parseInt(shortUrl.substring(shortUrl.lastIndexOf("/") + 1)); return map.get(key); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));
Using simple countercode
public class Codec { Map<Integer, String> map = new HashMap<>(); int i=0; 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/", ""))); } }
Using hashcodeip
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/", ""))); } }
Using random functionleetcode
public class Codec { Map<Integer, String> map = new HashMap<>(); Random r=new Random(); int key=r.nextInt(10000); public String encode(String longUrl) { while(map.containsKey(key)) key= r.nextInt(10000); map.put(key,longUrl); return "http://tinyurl.com/"+key; } public String decode(String shortUrl) { return map.get(Integer.parseInt(shortUrl.replace("http://tinyurl.com/", ""))); } }