膜拜大佬题解
https://www.bilibili.com/video/BV1CK411c7gx?p=16
过程分析
str的长度是m,pattern的长度是nF(i,j)的含义表示:str的前i位str[0,i-1]pattern的前j位pattern[0,j-1]是匹配的- 情况:
 p[j-1] = .或者p[j-1]= x,x表示任意一个小写字母,假如x=a。此时只要S[i-1]=a或者p[j-1]=.就可以转换成子问题
              
- 如果
S[i-1] != a直接返回false - 如果
p[j-1] = *,则需要考虑到p[j-2] 
                
                
- 如果
S[i-1] == p[j-2],或者 p[j-2] == .则需要匹配 
                
- 初始化问题
 s为空,p为空,返回true,则dp[0][0] = trues不空,p为空,均为false,则dp[i][0] = falsep不空,则需要计算
代码
#include <vector>
class Solution {
public:
    bool match(string str, string pattern) {
        int m = str.length();
        int n = pattern.length();
        vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
        dp[0][0] = true;
        for (int i = 2; i <= n; ++i) {
            if (pattern[i-1] == '*') {
                dp[0][i] = dp[0][i-2];
            }
        }
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (pattern[j-1] != '*' && (pattern[j-1] == '.' || pattern[j-1] == str[i-1])) {
                    dp[i][j] = dp[i-1][j-1];
                }
                else if (j >= 2 && pattern[j-1] == '*') {
                    if (pattern[j-2] == '.' || pattern[j-2] == str[i-1]) {
                        dp[i][j] = dp[i-1][j] || dp[i][j-2];
                    } else {
                        dp[i][j] = dp[i][j-2];
                    }
                }
            }
        }
        return dp[m][n];
    }
};

京公网安备 11010502036488号