diff --git a/Hard/10. Regular Expression Matching/soljava.java b/Hard/10. Regular Expression Matching/soljava.java deleted file mode 100644 index 1bf35e4..0000000 --- a/Hard/10. Regular Expression Matching/soljava.java +++ /dev/null @@ -1,32 +0,0 @@ -class Solution { - - - public boolean isMatch(String s, String p) { - int m = s.length(), n = p.length(); - Boolean[][] M = new Boolean[m+1][n]; // Why Boolean: null indicates the sub-problem not processed yet - return dfs(s, p, 0, 0, m, n, M); // The problem: to match s[i, m), p[j, n) - } - - - // the sub-problem: to match[i, m - - - private boolean dfs(String s, String p, int i, int j, int m, int n, Boolean[][] M) { - if (j == n) return i == m; - if (M[i][j] != null) return M[i][j]; - - char c2 = p.charAt(j); - if (j < n - 1 && p.charAt(j + 1) == '*') - return M[i][j] = dfs(s, p, i, j+2, m, n, M) || // do not match 'x*' , x means any char or . (use'*' as 0 char) - i < m && match(s.charAt(i), c2) && dfs(s, p, i+1, j, m, n, M); // match 1 char in string for '*' - - return M[i][j] = i < m && match(s.charAt(i), c2) && dfs(s, p, i+1, j+1, m, n, M); // match 1 char from both sides - } - - - private boolean match(char c1, char c2) { - if (c2 == '.') return true; - return c1 == c2; - } - -} \ No newline at end of file diff --git a/Medium/18. 4Sum/Solution.java b/Medium/18. 4Sum/Solution.java new file mode 100644 index 0000000..6dcc1e0 --- /dev/null +++ b/Medium/18. 4Sum/Solution.java @@ -0,0 +1,50 @@ +public class Solution { + public List> fourSum(int[] nums, int target) { + List> ans = new ArrayList<>(); + Arrays.sort(nums); + + for (int i = 0; i < nums.length - 3; i++) { + if (i > 0 && nums[i] == nums[i - 1]) { + continue; + } + + for (int j = i + 1; j < nums.length - 2; j++) { + if (j > i + 1 && nums[j] == nums[j - 1]) { + continue; + } + + int k = j + 1; + int l = nums.length - 1; + + while (k < l) { + long sum = (long) nums[i] + nums[j] + nums[k] + nums[l]; + + if (sum == target) { + List temp = new ArrayList<>(); + temp.add(nums[i]); + temp.add(nums[j]); + temp.add(nums[k]); + temp.add(nums[l]); + ans.add(temp); + + k++; + l--; + + while (k < l && nums[k] == nums[k - 1]) { + k++; + } + + while (k < l && nums[l] == nums[l + 1]) { + l--; + } + } else if (sum < target) { + k++; + } else { + l--; + } + } + } + } + return ans; + } +}