LeetCode 10. Regular Expression Matching

原題連接在這裏:https://leetcode.com/problems/regular-expression-matching/html

題目:express

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

'.' Matches any single character.
'*' Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true

題解:url

When it comes to two string, two array, with fixed position, asking count, max, min, true or false. It is likely to be dp.spa

Let dp[i][j] denotes matching result between s till index i-1 and p till index j-1.prototype

最後返回dp[s.length()][p.length()]. 因此dp生成時要設size成new boolean[s.length()+1][p.length()+1].code

狀態轉移時 若是當前的char能match上, dp[i][j] = dp[i-1][j-1].htm

不然的話若是p的當前char是'*', 要看p的前個char可否和s的當前char match上. 不能的話,這個'*'只能表明0個字符. dp[i][j] = dp[i][j-2].blog

若是能match上的話, 既能夠表明0個字符 dp[i][j-2] 也能夠表明多個字符 dp[i-1][j]. dp[i][j] = dp[i][j-2] || dp[i-1][j].element

Time Complexity: O(m*n). m = s.length(), n = p.length().

Space: O(m*n).

AC Java:

 1 public class Solution {
 2     public boolean isMatch(String s, String p) {
 3         int m = s.length();
 4         int n = p.length();
 5         boolean [][] dp = new boolean[m+1][n+1];
 6         dp[0][0] = true;
 7         
 8         for(int j = 1; j<=n; j++){
 9             if(p.charAt(j-1) == '*'){
10                 dp[0][j] = dp[0][j-2];
11             }
12         }
13         
14         for(int i = 1; i<=m; i++){
15             for(int j = 1; j<=n; j++){
16                 char sChar = s.charAt(i-1);
17                 char pChar = p.charAt(j-1);
18                 //如果首字符match
19                 if(sChar == pChar || pChar == '.'){
20                     dp[i][j] = dp[i-1][j-1];
21                 }else if(pChar == '*'){ //pattern 末尾是 * 
22                     //pattern * 前一個char 和 pChar match, 能夠是貪婪性減掉string的最後一char
23                     if(sChar == p.charAt(j-2) || p.charAt(j-2) == '.'){
24                         dp[i][j] = dp[i][j-2] | dp[i-1][j];
25                     }else{
26                         //pattern * 前一個 char 和pChar match不上,*表明0個preceding element
27                         dp[i][j] = dp[i][j-2];
28                     }
29                 }
30             }
31         }
32         return dp[m][n];
33     }
34 }

跟上Wildcard MatchingEdit Distance.

相關文章
相關標籤/搜索