[LeetCode] 10. Regular Expression Matching

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

DP: app

 1 public class Solution {
 2     public boolean isMatch2(String s, String p) {
 3         int starCnt = 0;
 4         for (int i = 0; i < p.length(); i++) {
 5             if (p.charAt(i) == '*') {
 6                 starCnt++;
 7             }
 8         }
 9         
10         boolean[] star = new boolean[p.length() - starCnt];
11         StringBuilder temp = new StringBuilder(p.length() - starCnt);
12         int index = -1;
13         for (int i = 0; i < p.length(); i++) {
14             if (p.charAt(i) == '*') {
15                 star[index] = true;
16             } else {
17                 temp.append(p.charAt(i));
18                 star[++index] = false;
19             }
20         }
21         String r = temp.toString();
22         
23         boolean[] lastRow = new boolean[s.length() + 1];
24         boolean[] curRow = new boolean[s.length() + 1];
25         boolean[] tempRow;
26         
27         lastRow[0] = true;
28         for (int i = 0; i < r.length(); i++) {
29             if (star[i] && lastRow[0]) {
30                 curRow[0] = true;
31             } else {
32                 curRow[0] = false;
33             }
34             
35             for (int j = 0; j < s.length(); j++) {
36                 if (!star[i]) {
37                     if ((r.charAt(i) == '.' || r.charAt(i) == s.charAt(j)) && lastRow[j]) {
38                         curRow[j + 1] = true;
39                     } else {
40                         curRow[j + 1] = false;
41                     }
42                 } else {
43                     if (lastRow[j + 1]) {
44                         curRow[j + 1] = true;
45                     } else if (lastRow[j] || curRow[j]) {
46                         if (r.charAt(i) == '.' || r.charAt(i) == s.charAt(j)) {
47                             curRow[j + 1] = true;
48                         } else {
49                             curRow[j + 1] = false;
50                         }
51                     } else {
52                         curRow[j + 1] = false;
53                     }
54                 }
55             }
56             
57             tempRow = lastRow;
58             lastRow = curRow;
59             curRow = tempRow;
60         }
61         
62         return lastRow[lastRow.length - 1];
63     }
64 }
相關文章
相關標籤/搜索