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") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true
Subscribe to see which companies asked this question.express
設匹配串爲s, 被匹配串爲p;this
class Solution { bool Match(size_t a, size_t b, const string &s, const string &p) { if(b == p.size()) return a == s.size(); if(b+1 < p.size()) { if(p[b+1] != '*') { if(s[a] == p[b] || p[b] == '.') return Match(a+1, b+1, s, p); else return false; } else { while(a < s.size() && (p[b] == s[a] || p[b] == '.')) { if(Match(a, b+2, s, p)) return true; a ++; } return Match(a, b+2, s, p); } } else { if(s[a] == p[b] || p[b] == '.') return Match(a+1, b+1, s, p); else return false; } } public: bool isMatch(string s, string p) { return Match((size_t)0, (size_t)0, s, p); } };