LeetCode #44

来源:互联网 发布:刺客信条大革命1.5优化 编辑:程序博客网 时间:2024/06/07 03:31

题目描述:

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.'*' Matches any sequence of characters (including the empty sequence).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", "*") → trueisMatch("aa", "a*") → trueisMatch("ab", "?*") → trueisMatch("aab", "c*a*b") → false
这题与前面的正则表达式匹配类似,不同在于‘*’可以匹配任意长度的字符串,而与前一个字符无关,为进行简化的话可以将连续的‘*’只保留一个,可以将算法的运行时间降低,所以这题用递归的方法更加简单。但是这题的测试案例比较复杂,由于递归的时间复杂度较高,部分案例超出了时间限制。

class Solution {public:    bool isMatch(string s, string p) {        p=continuous_star(p);        if(s.size()==0&&p.size()==0) return true;        else if(s.size()!=0&&p.size()==0) return false;        else if(s.size()==0&&p[0]=='*') return isMatch(s,p.substr(1));        else if(s.size()==0&&p[0]!='*') return false;        else if(s.size()!=0&&p.size()!=0)        {            if(p[0]!='*')            {                if(p[0]==s[0]||p[0]=='?') return isMatch(s.substr(1),p.substr(1));                else return false;            }            else if(p[0]=='*')            {                if(isMatch(s,p.substr(1))) return true;                else return isMatch(s.substr(1),p);            }        }    }        string continuous_star(string p)    {        for(int i=1;i<p.size();i++)        {            if(p[i-1]=='*'&&p[i]=='*')                 p=p.erase(i,1);        }        return p;    }};

为了减少运行时间,采用动态规划的方法,对于二维数组的初始化方式和递推方法都和之前正则表达式匹配有所不同,而且相对更简单一点:①将两个字符串首部添加空格字符,并对二维数组首行和首列进行初始化,便于递推。②1、当p[j]不为‘*’,则p[j]必须等于s[i],否则不能匹配。2、当p[j]为‘*’时,p[j]可以匹配任意长度的字符串,所以当x[i][j-1]为真,x[i][j]也为真,此时p[j]表示空字符串;同时如果x[i-1][j]为真时,x[i][j]也为真,即p[j]匹配的字符串增加一位,将s[i]也包括进去。递推结束后返回x[n-1][m-1]。

class Solution {public:    bool isMatch(string s, string p) {        s=" "+s;        p=" "+p;        int m=s.size();        int n=p.size();        bool x[m][n];        x[0][0]=true;        for(int i=1;i<m;i++)        {            x[i][0]=false;        }        for(int j=1;j<n;j++)        {            if(x[0][j-1]==true&&p[j]=='*')                x[0][j]=true;            else x[0][j]=false;        }        for(int i=1;i<m;i++)        {            for(int j=1;j<n;j++)            {                if(p[j]!='*')                {                    if((p[j]==s[i]||p[j]=='?')&&x[i-1][j-1]==true)                         x[i][j]=true;                    else x[i][j]=false;                }                else if(p[j]=='*')                {                    if(x[i][j-1]==true) x[i][j]=true;                    else if(x[i-1][j]==true) x[i][j]=true;                    else x[i][j]=false;                }            }        }        return x[m-1][n-1];    }};


原创粉丝点击