535.encode-and-decode-tinyurl.java 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. public class Codec {
  2. private int id = 0;
  3. private HashMap<Integer, String> map = new HashMap<>();
  4. // Encodes a URL to a shortened URL.
  5. public String encode(String longUrl) {
  6. String[] strs = longUrl.split("//");
  7. map.put(id, strs[0] + "/");
  8. StringBuilder sb = new StringBuilder();
  9. sb.append(id++);
  10. String[] body = strs[1].split("/", -1); // -1 means do not discard the last "" string
  11. for (String s : body) {
  12. map.put(id, s);
  13. sb.append(',');
  14. sb.append(id++);
  15. }
  16. return sb.toString();
  17. }
  18. // Decodes a shortened URL to its original URL.
  19. public String decode(String shortUrl) {
  20. String[] code = shortUrl.split(",");
  21. LinkedList<String> list = new LinkedList<>();
  22. for (String c : code) {
  23. int id = Integer.parseInt(c);
  24. String s = map.get(id);
  25. list.add(s);
  26. }
  27. String[] strs = list.toArray(new String[list.size()]);
  28. return String.join("/", strs);
  29. }
  30. }
  31. // Your Codec object will be instantiated and called as such:
  32. // Codec codec = new Codec();
  33. // codec.decode(codec.encode(url));