Regular Expression Matching - LeetCode

目录

题目链接

Regular Expression Matching - LeetCode

注意点

  • “.*”可以匹配任何字符串(包括空的)

解法

解法一:参考Regular Expression Matching 正则表达式匹配。时间复杂度为O(n)

class Solution {
public:
    bool firstCharIsMatch(char s,char p)
    {
        if(s == p || p == '.')
        {
            return true;
        }
        return false;
    }
    bool isMatch(string s, string p) {
        if(p.empty() == true)
        {
            return s.empty();
        }
        if(p.length()==1)
        {
            return (s.length()==1 && firstCharIsMatch(s[0],p[0]));
        }
        if(p[1] != '*')
        {
            if(s.empty() == true)
            {
                return false;
            }
            return firstCharIsMatch(s[0],p[0])&&isMatch(s.substr(1),p.substr(1));
        }
        while(!s.empty()&&firstCharIsMatch(s[0],p[0]))
        {
            if(isMatch(s,p.substr(2)) == true)
            {
                return true;
            }
            s = s.substr(1);
        }
        return isMatch(s,p.substr(2));
    }
};

小结

  • 第一反应是用C++11的regex库...用了之后发现效率还不如自己实现来得高

猜你喜欢

转载自www.cnblogs.com/multhree/p/10316396.html