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
这道题最麻烦的大概是理解题意,期初对于最后一个case百思不得其解,导致对于题目无从下手,后来查了Discuss,发现最早的问题就是关于这个case(稍微能够蠢蠢地自我安慰下了)。*并不是之后添加的意思,而是相当于对前面的字符进行说明,例如:
c*==(0个c---无限多个c) != (1个c---无限多个c);
在明白了这这点之后思路就比较清晰了;
首先:判断是不是两个均结束,倘若一方结束而另一方不是,return false;
之后:判断p下一位是否为*
不为*, 判断两位是否相同,或者*p为‘.’,且s此时不结束;如果相同进入下一位
为*,判断是否相同,相同则s++,当相同的位结束,p+2
不同,则直接p+2,即C*代表0个C的状态
这样的思路可以解决巨大多数的问题,除了(aaa,a*a),因此需要增加处理,即优先判断(s, p+2)是否匹配,如果匹配就return true;
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (*p == '\0') return *s == '\0';
if (*(p+1) != '*') {
return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s+1, p+1);
}
while ((*p == *s) || (*p == '.' && *s != '\0')) {
if (isMatch(s++, p+2)) return true;
}
return isMatch(s, p+2);
}
};