[LeetCode] 10. Regular Expression Matching

时间:2023-03-08 21:37:01

Implement regular expression matching with support for '.' and '*'.

DP:

 public class Solution {
public boolean isMatch2(String s, String p) {
int starCnt = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '*') {
starCnt++;
}
} boolean[] star = new boolean[p.length() - starCnt];
StringBuilder temp = new StringBuilder(p.length() - starCnt);
int index = -1;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '*') {
star[index] = true;
} else {
temp.append(p.charAt(i));
star[++index] = false;
}
}
String r = temp.toString(); boolean[] lastRow = new boolean[s.length() + 1];
boolean[] curRow = new boolean[s.length() + 1];
boolean[] tempRow; lastRow[0] = true;
for (int i = 0; i < r.length(); i++) {
if (star[i] && lastRow[0]) {
curRow[0] = true;
} else {
curRow[0] = false;
} for (int j = 0; j < s.length(); j++) {
if (!star[i]) {
if ((r.charAt(i) == '.' || r.charAt(i) == s.charAt(j)) && lastRow[j]) {
curRow[j + 1] = true;
} else {
curRow[j + 1] = false;
}
} else {
if (lastRow[j + 1]) {
curRow[j + 1] = true;
} else if (lastRow[j] || curRow[j]) {
if (r.charAt(i) == '.' || r.charAt(i) == s.charAt(j)) {
curRow[j + 1] = true;
} else {
curRow[j + 1] = false;
}
} else {
curRow[j + 1] = false;
}
}
} tempRow = lastRow;
lastRow = curRow;
curRow = tempRow;
} return lastRow[lastRow.length - 1];
}
}