Skip to content

Instantly share code, notes, and snippets.

@maydayco
Created June 7, 2013 15:32
Show Gist options
  • Save maydayco/5730141 to your computer and use it in GitHub Desktop.
Save maydayco/5730141 to your computer and use it in GitHub Desktop.
Regular Expression Matching
public class Solution {
public boolean isMatch(String s, String p) {
// Start typing your Java solution below
// DO NOT write main() function
boolean[][] sol = new boolean[s.length() + 1][p.length() + 1];
sol[0][0] = true;
for (int i = 2; i <= p.length(); i++) {
if (p.charAt(i - 1) == '*') {
sol[0][i] = sol[0][i - 2];
}
}
for (int i = 1; i <= s.length(); i++)
for (int j = 1; j <= p.length(); j++) {
if (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1)) {
sol[i][j] = sol[i - 1][j - 1];
} else if (p.charAt(j - 1) == '*' && j > 1 && sol[i][j - 2]) {
sol[i][j] = true;
} else if (p.charAt(j - 1) == '*' && (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1)))
sol[i][j] = sol[i - 1][j];
}
}
return sol[s.length()][p.length()];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment