美文网首页
[Leetcode] 42. Wildcard Matching

[Leetcode] 42. Wildcard Matching

作者: 时光杂货店 | 来源:发表于2017-03-20 19:57 被阅读4次

    题目

    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

    频度: 3、

    解题之法

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

    相关文章

      网友评论

          本文标题:[Leetcode] 42. Wildcard Matching

          本文链接:https://www.haomeiwen.com/subject/qhuinttx.html