LeetCode 10. Regular Expression Matching(hard)

来源:互联网 发布:苹果淘宝app打不开 编辑:程序博客网 时间:2024/05/22 16:04

题目描述

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”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “a*”) → true
isMatch(“aa”, “.*”) → true
isMatch(“ab”, “.*”) → true
isMatch(“aab”, “c*a*b”) → true

题目解析

实现正则表达式中的’.’和’*’。

第一种思路使用回溯的方法。参考代码

第二种,在回溯的基础上进一步用动态规划法加快速度。参考代码

代码(分治递归)

class Solution {public:    bool isMatch(string s, string p) {        return is_match(s.begin(),s.end(),p.begin(),p.end());    }    bool is_match(string::iterator s_bgn,string::iterator s_end,string::iterator p_bgn,string::iterator p_end)    {        if(s_end==s_bgn&&p_bgn==p_end)        {            return true;        }        if(s_end!=s_bgn&&p_bgn==p_end)        {            return false;        }        if(p_end-p_bgn>=2&&*(p_bgn+1)=='*')        {            //要么是s[0]可以匹配,继续匹配is_match(s[1:],p);            //或者在这里结束p*部分的匹配,继续is_match(s,p[2:]);            return ( is_match(s_bgn,s_end,p_bgn+2,p_end)||s_end!=s_bgn&&(*s_bgn==*p_bgn||*p_bgn=='.')&&is_match(s_bgn+1,s_end,p_bgn,p_end) );        }        else         {            //s[0]==p[0]或者s不为空且p[0]=='.';            //而且后续也要匹配            return ( (*p_bgn==*s_bgn||*p_bgn=='.'&&s_bgn!=s_end)&&is_match(s_bgn+1,s_end,p_bgn+1,p_end) );        }    }};

代码(动态规划)

class Solution {public:    bool isMatch(string s, string p) {        //记录所有is_match(s[:,i],p[:,j])的判断值        vector<vector<bool> >is_match(s.size()+1,vector<bool>(p.size()+1,false));        //s为空,p也为空时为真        is_match[0][0]=true;        for(int i=0;i<=s.size();i++)        {            for(int j=1;j<=p.size();j++)            {                if(p[j-1]!='*')//p[j-1]不为‘*’时,要求前面部分匹配的同时满足s[i-1]与p[j-1]匹配                {                    is_match[i][j] = i>0&&is_match[i-1][j-1]&&(p[j-1]==s[i-1]||p[j-1]=='.');                }                else//p[j-1]为‘*’时,出现两种情况:1)匹配0次,则只要前面匹配了就行;2)匹配一次以上,则要求前面匹配的同时此位匹配                {                    is_match[i][j] = is_match[i][j-2]||i>0&&is_match[i-1][j]&&(s[i-1]==p[j-2]||p[j-2]=='.');                }            }        }        return is_match[s.size()][p.size()];    }};
0 0