public class Codec { private int id = 0; private HashMap map = new HashMap<>(); // Encodes a URL to a shortened URL. public String encode(String longUrl) { String[] strs = longUrl.split("//"); map.put(id, strs[0] + "/"); StringBuilder sb = new StringBuilder(); sb.append(id++); String[] body = strs[1].split("/", -1); // -1 means do not discard the last "" string for (String s : body) { map.put(id, s); sb.append(','); sb.append(id++); } return sb.toString(); } // Decodes a shortened URL to its original URL. public String decode(String shortUrl) { String[] code = shortUrl.split(","); LinkedList list = new LinkedList<>(); for (String c : code) { int id = Integer.parseInt(c); String s = map.get(id); list.add(s); } String[] strs = list.toArray(new String[list.size()]); return String.join("/", strs); } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.decode(codec.encode(url));