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
实现个简单的正则匹配,支持'.'与'*'的操作
解决这题的关键是思路要清晰,考虑要周全。
1. 递归实现。
思路:
isMatch(s, p):
1. 当前p为0时,若s也是0时,则返回true,否则为false
2. 当前p不为0时,
1) p的下一个不是'*'时
if: 当前s与p匹配,
则表明到此都是匹配的,只需要检查isMatch(s + 1, p + 1)
else:
返回false
2) p的下一个是'*'时,
while: 当前s与p匹配,即表明至此也是匹配的
if: 当前s与下一个p也都匹配,即isMatch(s, p + 2),则返回true
else: s++
此时,当前s与当前p已经不匹配了(之前s都是匹配的),则检测下一个模板isMatch(s, p + 2)
代码如下:
1 class Solution { 2 public: 3 bool isMatch(const char *s, const char *p) { 4 if (*p == '