-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
https://leetcode.com/problems/regular-expression-matching/
- Loading branch information
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
41 changes: 41 additions & 0 deletions
41
interview_prep/algorithm/java/ide_handicapped/regular_expression_matching/Solution.java
This file contains 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
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; | ||
} | ||
} |