Skip to content

Commit

Permalink
https://leetcode.com/problems/regular-expression-matching/
Browse files Browse the repository at this point in the history
  • Loading branch information
s50600822 committed Dec 4, 2023
1 parent 63b1cbf commit 122c02a
Showing 1 changed file with 41 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;

for (int i = 1; i <= m; i++) {
dp[i][0] = false;
}

for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 2];
} else {
dp[0][j] = false;
}
}

for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
char sc = s.charAt(i - 1), pc = p.charAt(j - 1);
if (pc == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else if (pc == '*') {
dp[i][j] = dp[i][j - 2] || ((sc == p.charAt(j - 2) || p.charAt(j - 2) == '.') && dp[i - 1][j]);
} else {
dp[i][j] = (sc == pc) && dp[i - 1][j - 1];
}
}
}

return dp[m][n];
}

public static void main(String[] args) {
Solution self = new Solution();
assert self.isMatch("aa", "a") == false;
assert self.isMatch("aa", "a*") == true;
assert self.isMatch("aa", ".*") == true;
}
}

0 comments on commit 122c02a

Please sign in to comment.