LeetCode

来源:互联网 发布:锁屏主题软件 编辑:程序博客网 时间:2024/06/08 10:54

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).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", "a*") → trueisMatch("aa", ".*") → trueisMatch("ab", ".*") → trueisMatch("aab", "c*a*b") → true


递归的思路比较好理解,如果当前位置互相匹配,就往后继续匹配。

字母相同或者'.'都好办,因为都是一位,'*'比较麻烦,因为他可以匹配任意多位。

所以不为'*'的时候,只要继续往后匹配即可;若是为'*',要么当前的字符作废,没有出现过,继续往后匹配;要么s不为空,前一个位置可以匹配的上,然后s往后匹配,p位置不动。

class Solution {public:    bool isMatch(string s, string p) {        if (p.empty()) return s.empty();                // x* matches empty string or at least one character: x* -> xx*        // *s is to ensure s is non-empty        if (p[1] == '*')            return isMatch(s, p.substr(2)) || !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p);        return !s.empty() && (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));    }};
还有个dp的做法

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

原创粉丝点击