LeetCode Regular Expression Matching

来源:互联网 发布:在vb中chr是什么意思 编辑:程序博客网 时间:2024/06/03 07:05

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
思路一:最先想到的是直接进行处理,处理各种可能出现的状况。这样实现起来编程难度较大,逻辑清晰也蛮难的,很难一次性bug free


思路二:通过分析不难发现,判别是否匹配实际上是一种状态的转换,然后就联想到了动态规划。使用动态规划之前,我们需要理清所求解问题的动态方程:

初始条件:dp[0][0] = true; dp[i][0] = false, i < s.length+1;dp[0][i] = i> 1 && p[i-1] == '*' && p[0][i-2];

动态方程:if p[j-1] == '*' then p[i][j] = p[i][j-2]&&(p[j-2] == '.' || p[i-2] == s[i-1]) && p[i-1][j];

 else then p[i][j] = p[i-1][j-1] && (s[i-1] == p[j-1] || p[j-1] == '.');

代码如下:

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


动态规划真是个好东西

0 0
原创粉丝点击