LeetCode

来源:互联网 发布:js 点击图片放大 编辑:程序博客网 时间:2024/06/11 15:02

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") → falseisMatch("aa","aa") → trueisMatch("aaa","aa") → falseisMatch("aa", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false

?可以匹配单个字符,*可以匹配任意个字符。

写了个递归,然后TLE了,嗯。。于是开始搞dp。

f[i][j]表示 s[0, i)  p[0, j) 的匹配

当p[i-1] != '*',f[i][j] = f[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '?') 
当p[i-1] == '*',f[i][j] = f[i-1][j] || f[i][j-1] 

最开始预处理的时候出了点问题,没处理好一直wa,重点标记一下。

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