leetcode No10. Regular Expression Matching

来源:互联网 发布:linux cpu 内存 查看 编辑:程序博客网 时间:2024/05/21 14:56

Question:

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

Algorithm:

设当前字符串s1的下标为i,s2的下标为j
1、s2[i+1]!=' * ',只需往后一一比对
2、s2[i+1]==' * ',分两种情况
(1)s1[i]!=s2[j],相当于后面的*是把s[j]的出现次数置为0,再比对s1[i]和s2[j+2]
(2)s1[i]==s2[j],那么就要维持现有的模式(i++,j位置不变)或置为(1)

Accepted Code:

C:
bool isMatch(char* s, char* p) {    if(*s=='\0' && *p=='\0')        return true;    if(*s!='\0' && *p=='\0')        return false;    if(*(p+1)!='*')    {        if((*s!='\0') && (*s==*p || *p=='.'))               return isMatch(s+1,p+1);        else            return false;    }    else    {        while((*s!='\0') && (*s==*p || *p=='.'))        {            if(isMatch(s,p+2))                return true;            s++;        }        return isMatch(s,p+2);    }    return false;}

C++:这个速度很慢,不知道为啥???用了289ms
class Solution {public:    bool isMatch(string s, string p) {        return helper(s,p,0,0);    }    bool helper(string s1,string s2,int i,int j)    {        if(j==s2.size())            return i==s1.size();        if(s2[j+1]!='*')        {            if(s1[i]==s2[j] || s2[j]=='.')                return helper(s1,s2,i+1,j+1) ;        }        else        {            while(i<s1.size() && (s1[i]==s2[j] || s2[j]=='.'))            {                if(helper(s1,s2,i,j+2))                    return true;                i++;            }            return helper(s1,s2,i,j+2);        }        return false;    }};


0 0
原创粉丝点击