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
分情况用递归解决。
首先便携式一个函数判断s和p当前字符匹配是否匹配:若字符相同或p为’.’,则”s和p当前字符匹配”。
1、若p为空,若s也为空,返回true,反之返回false;
2、若p的长度为1,若s长度也为1,且”s和p当前字符匹配”,则返回true,反之返回false;
3、若p的第二个字符不为’*’,若此时s为空返回false,否则若”s和p当前字符匹配”,再从各自的第二个字符开始调用递归函数匹配;
4、若p的第二个字符为’*’,若”s和p当前字符匹配”,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母继续上述匹配过程;
5、返回调用递归函数匹配s和去掉前两个字符的p的结果;
bool SMatchP(char s,char p){
return s == p || p == '.';
}
bool isMatch(string s, string p) {
if(p.empty())
return s.empty();
if(p.size() == 1)
return (s.size() == 1 && SMatchP(s[0],p[0]));
if(p[1] != '*'){
if(s.empty())
return false;
return SMatchP(s[0],p[0]) && isMatch(s.substr(1), p.substr(1));
}
while (!s.empty() && SMatchP(s[0],p[0])) {
if(isMatch(s,p.substr(2)))
return true;
s = s.substr(1);
}
return isMatch(s, p.substr(2));
}