邓心一 6 năm trước cách đây
mục cha
commit
9e936afb20

+ 29 - 0
hard/140.word-break-ii.java

@@ -0,0 +1,29 @@
+import java.util.*;
+
+class Solution {
+    public List<String> wordBreak(String s, List<String> wordDict) {
+        HashMap<String, List<String>> map = new HashMap<>();
+        return dfs(s, wordDict, map);
+    }
+
+    private List<String> dfs(String s, List<String> wordDict, HashMap<String, List<String>> map) {
+        List<String> res;
+        if ((res = map.get(s)) != null) return res;
+        res = new ArrayList<>();
+        if (s.equals("")) {
+            res.add("");
+            return res;
+        }
+        for (String word : wordDict) {
+            if (s.startsWith(word)) {
+                List<String> list = dfs(s.substring(word.length()), wordDict, map);
+                for (String suffix : list) {
+                    if (suffix.equals("")) res.add(word);
+                    else res.add(word + " " + suffix);
+                }
+            }
+        }
+        map.put(s, res);
+        return res;
+    }
+}

+ 4 - 4
hard/32.longest-valid-parentheses.java

@@ -6,16 +6,16 @@ class Solution {
         Stack<Integer> stack = new Stack<>();
         Stack<Integer> stack = new Stack<>();
         int max = 0, pre = -1;
         int max = 0, pre = -1;
         for (int i = 0; i < chs.length; i++) {
         for (int i = 0; i < chs.length; i++) {
-            if (chs[i] == '(') {
+            char ch = chs[i];
+            if (ch == '(') {
                 stack.push(i);
                 stack.push(i);
                 continue;
                 continue;
-            }
-            if (stack.empty()) {
+            } else if (stack.isEmpty()) {
                 pre = i;
                 pre = i;
                 continue;
                 continue;
             }
             }
             stack.pop();
             stack.pop();
-            if (stack.empty()) max = Math.max(max, i - pre);
+            if (stack.isEmpty()) max = Math.max(max, i - pre);
             else max = Math.max(max, i - stack.peek());
             else max = Math.max(max, i - stack.peek());
         }
         }
         return max;
         return max;