File tree 1 file changed +40
-0
lines changed
Leetcode - Top Interview Questions
1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public boolean isMatch (String s , String p ) {
3
+ boolean [][] dp = new boolean [s .length () + 1 ][p .length ()+1 ];
4
+ dp [0 ][0 ] = true ;
5
+
6
+ // initialize first column and row
7
+ for (int i = 1 ; i <= p .length (); i ++) {
8
+ dp [0 ][i ] = p .charAt (i - 1 ) == '*' && dp [0 ][i - 2 ];
9
+ }
10
+
11
+ for (int i = 1 ; i <= s .length (); i ++) {
12
+ dp [i ][0 ] = false ;
13
+ }
14
+
15
+ for (int i = 1 ; i <= s .length (); i ++) {
16
+ for (int j = 1 ; j <= p .length (); j ++) {
17
+ if (p .charAt (j - 1 ) == '*' ) {
18
+ // we use * to match current character in string i
19
+ // aaa -> aa dp[i][j] = dp[i-1][j]
20
+ // a* -> a*
21
+ if (s .charAt (i - 1 ) == p .charAt (j - 2 ) || p .charAt (j - 2 ) == '.' ) {
22
+ dp [i ][j ] = dp [i -1 ][j ];
23
+ }
24
+ // ?* match 0 cahracters
25
+ // aa
26
+ // aab*
27
+ dp [i ][j ] = dp [i ][j - 2 ] || dp [i ][j ];
28
+ } else {
29
+ // ease case
30
+ if (s .charAt (i - 1 ) == p .charAt (j - 1 ) || p .charAt (j - 1 ) == '.' ) {
31
+ dp [i ][j ] = dp [i - 1 ][j - 1 ];
32
+ }
33
+ }
34
+ }
35
+ }
36
+ return dp [s .length ()][p .length ()];
37
+ }
38
+
39
+
40
+ }
You can’t perform that action at this time.
0 commit comments