(算法分析Week9)Regular Expression Matching[Hard]

来源:互联网 发布:石狮优浮网络会所 编辑:程序博客网 时间:2024/05/22 06:33

10.Regular Expression Matching[Hard]

题目来源

Description

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

Solution

动态规划Tag里的题目,但是我第一反应是用递归做,所以就试了试递归,居然能AC。
递归:
分情况讨论,p为空直接返回。
p为1就比较第一个,可以相等可以为‘.’。

由于’*’匹配一个或多个在它之前的字符,若p的第二个字符为’*’,s不为空且第一个字符匹配,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母(已经匹配好的)再和pattern比较。

若不为’*’,就都去掉第一个字符然后递归。

动态规划:

自己是没想出什么好方法,看到discuss有一个说的不错,直接搬运。
Easy DP Java Solution with detailed Explanation

Complexity analysis

O(M*N)
M = s.length()
N = p.length()

Code

(1)递归class Solution {public:    bool isMatch(string s, string p) {        if (p.empty()) return s.empty();        if (p.size() == 1) {            return (s.size() == 1 && (s[0] == p[0] || p[0] == '.'));        }        if (p[1] != '*') {            if (s.empty()) return false;            return (s[0] == p[0] || p[0] == '.') && isMatch(s.substr(1), p.substr(1));        }        while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {            if (isMatch(s, p.substr(2))) return true;            s = s.substr(1);        }        return isMatch(s, p.substr(2));    }};(2)动态规划class Solution {public:    bool isMatch(string s, string p) {        int M = s.length(), N = p.length();         vector<vector<bool> > dp(M + 1, vector<bool> (N + 1, false));        dp[0][0] = true;        for (int i = 0; i <= M; i++)            for (int j = 1; j <= N; j++)                if (p[j - 1] == '*')                    dp[i][j] = dp[i][j - 2] || (i > 0 && (s[i - 1] == p[j - 2] || p[j - 2] == '.') && dp[i - 1][j]);                else dp[i][j] = i > 0 && dp[i - 1][j - 1] && (s[i - 1] == p[j - 1] || p[j - 1] == '.');        return dp[M][N];    }};

Result

这里写图片描述

阅读全文
0 0
原创粉丝点击