【Leetcode】【Regular Expression Matching】【正则表达式匹配】【C++】

  • 题目:给定一个字符串 (s) 和一个字符模式 (p)。实现支持 '.' 和 '*' 的正则表达式匹配。
    '.' 匹配任意单个字符。
    '*' 匹配零个或多个前面的元素。
  • 说明:
    • s 可能为空,且只包含从 a-z 的小写字母。
    • p 可能为空,且只包含从 a-z 的小写字母,以及字符 . 和 *
  • 思路:多层递归易超时,需优化
  • 代码:
    class Solution {
    public:
        bool isMatch(string s, string p) {
            if(s=="" && p=="")
                return true;
            else if(p=="" )
                return false;
            int len_s=s.size();
            int len_p=p.size();
    
            if(len_p==1)
            {
                if(len_s==1)
                {
                    if(s[0]==p[0] || p[0]=='.')
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            if(p[1]!='*')
            {
                if(s.size()==0)
                    return false;
                if(p[0]==s[0] || p[0]=='.')
                {
                    string s1(s,1);
                    string p1(p,1);
                    return isMatch(s1,p1);
                }
                else
                    return false;
            }
            else
            {
                string s1="";
                string p1(p,2);
                if(s!="")
                {
                    string temp(s,1);
                    s1=temp;
                }
                else
                    return isMatch(s,p1);
    
                if(p[0]==s[0] || p[0]=='.')
                {
                    return isMatch(s,p1) || isMatch(s1,p1) || isMatch(s1,p);
                }
                else
                    return isMatch(s,p1);
            }
    
    
        }
    };

    其中,

     else
            {
                string s1="";
                string p1(p,2);
                if(s!="")
                {
                    string temp(s,1);
                    s1=temp;
                }
                else
                    return isMatch(s,p1);
    
                if(p[0]==s[0] || p[0]=='.')
                {
                    return isMatch(s,p1) || isMatch(s1,p1) || isMatch(s1,p);
                }
                else
                    return isMatch(s,p1);
            }

    需替换为

  • else
            {
                string s1="";
                string p1(p,2);
                if(s!="")
                {
                    string temp(s,1);
                    s1=temp;
                }
                else
                    return isMatch(s,p1);
    
                while (!s.empty() && (s[0] == p[0] || p[0] == '.')) {
                if (isMatch(s, p.substr(2))) return true;
                s = s.substr(1);
                }
                return isMatch(s,p1);
            }

猜你喜欢

转载自www.cnblogs.com/dreamer123/p/9170756.html
今日推荐