[leetcode]10. Regular Expression Matching

链接:https://leetcode.com/problems/regular-expression-matching/description/


Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

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

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

Note:

  • s could be empty and contains only lowercase letters a-z.
  • p could be empty and contains only lowercase letters a-z, and characters like . or *.

Example 1:

Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".

Example 2:

Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".

Example 3:

Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".

Example 4:

Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".

Example 5:

Input:
s = "mississippi"
p = "mis*is*p*."
Output: false

用bool型二维数组vvb[i][j]表示s的前i个字符和p的前j个字符是否匹配。

初始值,dp[0][0]为true,dp[0][j]的值取决于p前一个位置是否为‘*’以及前一情况是否匹配。

当p[j]等于‘.’或者s[i]等于p[j]时,则dp[i][j]的值取决于dp[i-1][j-1],即为s的前一位置和p的前一位置是否匹配;

当p[j]等于‘*’时,分两种情况:

(1)如果s[i]!=p[j-1] 以及p[j-1]!='.' ,则 dp[i][j]=dp[i][j-2]

(2)如果 s[i]!=p[j-1] 或p[j-1]!='.' ,则dp[i][j]= dp[i][j-2] (a* 指的是空)

                                                    或者dp[i][j]= dp[i][j-1] (a* 指的是单个a)

                                                    或者dp[i][j]= dp[i-1][j] (a* 指的是多个a)


class Solution {
public:
    bool isMatch(string s, string p) {
        vector<vector<bool>> dp(s.size()+1, vector<bool>(p.size()+1, false));
        dp[0][0] = true;
        
        for(int j=1; j<=p.size(); j++)
        {
            if(p[j-1]=='*' && dp[0][j-2])
                dp[0][j] = true;
           
        }
        
        for (int i=1; i<=s.size(); i++)
        {
            for (int j=1; j<=p.size(); j++)
            {
                if (s[i-1] == p[j-1] || p[j-1] == '.')
                    dp[i][j] = dp[i-1][j-1];
                else if (p[j-1] == '*')
                {
                    if(s[i-1]!=p[j-2] && p[j-2]!='.')
                        dp[i][j]=dp[i][j-2];
                    else if (s[i-1]==p[j-2] || p[j-2]=='.')
                        dp[i][j] = dp[i][j-1] || dp[i-1][j] || dp[i][j-2];
                }
            }
        }
        
        return dp[s.size()][p.size()];
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/80302641