leetcode: Regular Expression Matching
http://oj.leetcode.com/problems/regular-expression-matching/
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 |
思路:
关键在于'*'的处理。对于类似于"a*"的情况,我们可以匹配0个'a',也可以匹配尽可能多的'a'。
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 if ('\0' == *p) { 5 return '\0' == *s; 6 } 7 8 if ('*' == *(p + 1)) { 9 while ((*s != '\0') && ((*s == *p) || ('.' == *p))) { 10 if (isMatch(s, p + 2)) { 11 return true; 12 } 13 14 ++s; 15 } 16 17 return isMatch(s, p + 2); 18 } 19 else { 20 if ((*s != '\0') && ((*s == *p) || ('.' == *p))) { 21 return isMatch(s + 1, p + 1); 22 } 23 24 return false; 25 } 26 } 27 };