正则表达式 困难模式
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 ‘.’ 和 ‘*’ 的正则表达式匹配。
‘.’ 匹配任意单个字符
‘*’ 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。
大佬解法:递归
涉及到动态规划,第一次遇到此类题,完全没想到,记录下来,以供学习。
// 优化后的版本 20ms
class Solution {
public:
bool isMatch(string s, string p) {
return isMatch(s.c_str(), p.c_str());
}
bool isMatch(const char* s, const char* p) {
if(*p == 0) return *s == 0;
auto first_match = *s && (*s == *p || *p == '.');
if(*(p+1) == '*'){
return isMatch(s, p+2) || (first_match && isMatch(++s, p));
}
else{
return first_match && isMatch(++s, ++p);
}
}
};