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
思路:只有当模式串和字符串同时等于\0,才可以认为两个串匹配。
在匹配中,对于每个位的匹配可以分为三种情况
1、(相应位匹配||模式串为.&&字符串不是\0)&&模式串下一位是*
2、(相应位匹配||模式串为.&&字符串不是\0)&&模式串下一位不是*
3、相应位不匹配&&(模式位不为.||字符串是\0)
对应1,最复杂。分为*取0,*取1,*>=2三种情况。
*取0对应跳过当前匹配位,继续寻找patter的下一个匹配位,str不变,pattern+2
*取1对应当前匹配位算一次成功匹配,str+1,pattern+2
*取>=2对应一次成功匹配,继续匹配字符串的下一位是否匹配,str+1,pattern不变
三者取或。即只要有一种情况能匹配成功认为字符串就是匹配成功的。
对应2,相当于一次成功匹配,str+1,pattern+1
对应3,匹配失败,直接返回false
bool isSubMatch(string& s, int pos1, string& p, int pos2){
if (pos1 == s.size() && pos2 == p.size())return true;
if (pos1 != s.size() && pos2 == p.size())return false;
if (p[pos2 + 1] == '*'){
if (s[pos1] == p[pos2] || (p[pos2] == '.' && pos1 != s.size())){
return isSubMatch(s, pos1, p, pos2 + 2) || isSubMatch(s, pos1 + 1, p, pos2);
}
else
return isSubMatch(s, pos1, p, pos2 + 2);
}
if (s[pos1] == p[pos2] || (p[pos2] == '.' && pos1 != s.size()))
return isSubMatch(s, pos1 + 1, p, pos2 + 1);
return false;
}
bool isMatch(string s, string p) {
if (s == "" || p == "")return false;
return isSubMatch(s, 0, p, 0);
}