LeetCode 44. Wildcard Matching--动态规划

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/monkey_rose/article/details/79053773

题目链接

44Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

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", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false
解:果然是字符串的问题都可以用dp来解,dp[i][j]代表的含义是s前i个字符的子串和p的前j个字符的子串是否匹配,如果是dp[0][j]那么代表空串和非空串的匹配,“”和“”或连续的‘*’可以匹配。
dp状态转移:
1)s[i-1] == '*'  => dp[i-1][0]...dp[i-1][j]中有一个为true,dp[i][j] = true
2)p[j-1] == '*'  => dp[0][j-1]...dp[i][j-1]中一个为true,dp[i][j] = true
3)s[i-1] 同 p[j-1]字符相匹配,'?'或者其他的相同字符  => dp[i][j] = dp[i-1][j-1]
4)s[i-1] 同 p[j-1]字符不匹配  => dp[i][j] = false
代码:
class Solution {
public:
    bool isMatch(string s, string p) {
        int size_s = s.length();
        int size_p = p.length();
        vector<vector<bool> > dp(size_s+1, vector<bool>(size_p+1, false));
        dp[0][0] = true;
        for (int i = 1; i <= size_s; i++) dp[i][0] = s[i-1] == '*' && dp[i-1][0] ? true : false;
        for (int i = 1; i <= size_p; i++) dp[0][i] = p[i-1] == '*' && dp[0][i-1] ? true : false;
        for (int i = 1; i <= size_s; i++) {
            for (int j = 1; j <= size_p; j++) {
                if (s[i-1] == '*') {
                    for (int t = 0; t <= j; t++) dp[i][j] = dp[i][j] || dp[i-1][t];
                }
                if (p[j-1] == '*') {
                    for (int t = 0; t <= i; t++) {
                     	dp[i][j] = dp[i][j] || dp[t][j-1];
                    }
                    continue;
                }
                if(s[i-1] == '?' || p[j-1] == '?' || s[i-1] == p[j-1]) dp[i][j] = dp[i][j] || dp[i-1][j-1];
                else dp[i][j] = false;
            }
        }
        return dp[size_s][size_p];
    }
};



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页