Created
November 13, 2017 14:37
-
-
Save shailrshah/1201e3a90fc194f79c8385cd90ce03b1 to your computer and use it in GitHub Desktop.
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public boolean isMatch(String str, String pat) { | |
char[] s = str.toCharArray(); | |
char[] p = pat.toCharArray(); | |
boolean[][] dp = new boolean[s.length+1][p.length+1]; | |
dp[0][0] = true; | |
for(int j = 1; j < dp[0].length; j++) { // For cases like (a, a*) | |
if(p[j-1] == '*') | |
dp[0][j] = dp[0][j-2]; | |
} | |
for(int i = 1; i < dp.length; i++) { | |
for(int j = 1; j < dp[0].length; j++) { | |
if(p[j-1] == '.' || s[i-1] == p[j-1]) | |
dp[i][j] = dp[i-1][j-1]; | |
else if(p[j-1] == '*') { | |
dp[i][j] = dp[i][j-2]; | |
if(s[i-1] == p[j-2] || p[j-2] == '.') | |
dp[i][j] = dp[i][j] || dp[i-1][j]; | |
} | |
else | |
dp[i][j] = false; | |
} | |
} | |
return dp[s.length][p.length]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment