10. Regular Expression Matching

好难啊 https://leetcode.com/problems/regular-expression-matching/discuss/180290/JAVA-DP-solution-with-detailed-explanation

 

 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        for(int i = 1; i <= p.length(); i++){
 6            if(p.charAt(i-1) == '*' && dp[0][i-2]){
 7                dp[0][i] = true;
 8            }
 9        }
10         
11         for(int i = 1; i <= s.length(); i++){
12             for(int j = 1; j <= p.length(); j++){
13                 if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.'){
14                     dp[i][j] = dp[i-1][j-1];
15                 }else if(p.charAt(j-1) == '*'){
16                     if(p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.'){
17                         dp[i][j] = dp[i][j-2];
18                     }else{
19                         dp[i][j] = dp[i][j-1] || dp[i-1][j] || dp[i][j-2];
20                     }
21                 }
22             }
23         }
24         return dp[s.length()][p.length()];
25         
26     }
27 }

 

posted @ 2018-10-21 13:21  jasoncool1  阅读(115)  评论(0编辑  收藏  举报