dengxinyi 6 年之前
父節點
當前提交
5b8d3542a1
共有 1 個文件被更改,包括 36 次插入0 次删除
  1. 36 0
      medium/535.encode-and-decode-tinyurl.java

+ 36 - 0
medium/535.encode-and-decode-tinyurl.java

@@ -0,0 +1,36 @@
+public class Codec {
+    private int id = 0;
+    private HashMap<Integer, String> 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<String> 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));