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
class Solution {
public:
bool isMatch(string s, string p) {
if( !p.length() ) return s.length() == 0;
//都不为空
if( (s[0] == p[0] || (p[0] == '.' && s.length()) ) && p[1] != '*') return isMatch( s.substr(1), p.substr(1));
else if( p[1] == '*') //C*也表示 0个C
{
int i = 0;
while( s[i] == p[0] || ( p[0] == '.' && s.substr(i).length()) )
{
if( isMatch(s.substr(i++),p.substr(2)) )
return true;
}
return isMatch(s.substr(i),p.substr(2));
}
else return false;
}
};