Leetcode(9)

来源:互联网 发布:举报网络涉赌 编辑:程序博客网 时间:2024/06/07 05:12

https://leetcode.com/problems/regular-expression-matching/#/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:

解题思路是使用动态规划,动态规划将一个大问题划分为多个小问题来递归求解,为加快运算速度,我们会保存中间的小问题的结果。

首先,我们先创建一个布尔矩阵dp(行为字符串,列为正则表达式),并进行初始化:

1、[0][0]设为正确,意为两者都为空。

2、[i][0]设为错误,意为正则表达式为空而字符串不为空。

3、[0][j]根据情况而设:

a、当p[j - 1] == '*'时,取[i][j - 2]的值(去除j == 1的情况)。

b、当p[j - 1] != '*'时,必为错误。


接着,我们就可以进行判断了,分为两种大情况:

1、当前正则不为'*',满足条件当前字符相等,或当前正则字符为'.',并且[i - 1][j - 1]正确的,则为正确。

2、当前正则为'*',考虑两种情况,满足任一条件即可:

a) [i][j - 2]为True,这种情况为p[j -2]*当作empty跳过

b) p[j - 2] 为 '.' 或p[j - 2] == s[i - 1],且dp[i - 1][j]为True,这种情况为重复p[j-2]

最后返回右下角的bool。

class Solution2 {public:    bool isMatch(string s, string p) {        if (p.length() == 0) return s.length() == 0;        bool dp[s.length() + 1][p.length() + 1];        //initial        dp[0][0] = true;        for(int i = 1; i < s.length() + 1; i++) {            dp[i][0] = false;        }        for(int j = 1; j < p.length() + 1; j++) {            if(j > 1 && p[j - 1] == '*') {                dp[0][j] = dp[0][j - 2];            } else {                dp[0][j] = false;            }        }        //dynamic programing        for(int i = 1; i < s.length() + 1; i++) {            for (int j = 1; j < p.length() + 1; j++) {                if(p[j - 1] != '*') {                    // case not *                    if(p[j - 1] == '.') {                        dp[i][j] = dp[i - 1][j - 1];                    } else {                        dp[i][j] = dp[i - 1][j - 1] && s[i - 1] == p[j - 1];                    }                } else {                    // case *                    if (dp[i][j - 2]) {                        dp[i][j] = true;                    } else {                        dp[i][j] = dp[i - 1][j] && (p[j - 2] == '.' || p[j - 2] == s[i - 1]);                    }                }            }        }        for(int i = 0; i < s.length() + 1; i++) {            for (int j = 0; j < p.length() + 1; j++) {                cout << dp[i][j] << "\t";            }            cout << endl;        }        return dp[s.length()][p.length()];    }};


0 0
原创粉丝点击