Skip to content

Instantly share code, notes, and snippets.

@vaibhav93
Created December 10, 2017 23:12
Show Gist options
  • Select an option

  • Save vaibhav93/746c444e33f4a9cc9ee4c73807190079 to your computer and use it in GitHub Desktop.

Select an option

Save vaibhav93/746c444e33f4a9cc9ee4c73807190079 to your computer and use it in GitHub Desktop.
class Solution {
public boolean isMatch(String s, String p) {
char[] text = s.toCharArray();
char[] pattern = p.toCharArray();
boolean T[][] = new boolean[text.length + 1][pattern.length + 1];
T[0][0] = true;
//Deals with patterns like a* or a*b* or a*b*c*
for (int i = 1; i < T[0].length; i++) {
if (pattern[i-1] == '*') {
T[0][i] = T[0][i - 2];
}
}
for (int i = 1; i < T.length; i++) {
for (int j = 1; j < T[0].length; j++) {
// First check if the current chars match. match is also considered for dot. if yes
// remove these two and see prev i-1 j-1 in matrix
if (pattern[j - 1] == '.' || pattern[j - 1] == text[i - 1]) {
T[i][j] = T[i-1][j-1];
}
// Now if the current pattern is star.
else if (pattern[j - 1] == '*') {
// We can remve the star and previous char from patter. assuming its zero occurence
// in that case we check if before that was a match
T[i][j] = T[i][j - 2];
if (pattern[j-2] == '.' || pattern[j - 2] == text[i - 1]) {
T[i][j] = T[i][j] | T[i - 1][j];
}
} else {
T[i][j] = false;
}
}
}
return T[text.length][pattern.length];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment