Skip to content

Commit

Permalink
Add 10-Regular-Expression-Matching
Browse files Browse the repository at this point in the history
  • Loading branch information
miladra committed Aug 27, 2022
1 parent 2587b27 commit e99ae2b
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions java/10-Regular-Expression-Matching.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
class Solution {

public boolean isMatch(String s, String p) {

boolean[][] cache = new boolean[s.length() + 1][p.length() + 1];

return dfs(cache , s, p, 0 , 0);
}

private boolean dfs(boolean[][] cache, String s, String p , int i, int j) {

if(cache[i][j] != false)
return cache[i][j];

if( i >= s.length() && j>= p.length())
return true;

if(j >= p.length())
return false;

boolean match = i < s.length() && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.');

if(j + 1 < p.length() && p.charAt(j+1)== '*' ) {
cache[i][j] = dfs(cache, s, p, i, j+2) || (match && dfs(cache, s, p, i+1, j));
} else {
cache[i][j] = match && dfs(cache, s, p, i+1, j+1);
}

return cache[i][j];
}
}

0 comments on commit e99ae2b

Please sign in to comment.