Regular Expression Matching - LeetCode

題目連接

Regular Expression Matching - LeetCodehtml

注意點

  • 「.*」能夠匹配任何字符串(包括空的)

解法

解法一:參考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庫...用了以後發現效率還不如本身實現來得高
相關文章
相關標籤/搜索