static const auto __speedup_ = []() {
std::cout.sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();
/*
用遞歸的算法:注意邊界條件的討論
原問題如下:
Given an input string (s) and a pattern (p), 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).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
*/
class Solution {
public:
// 用p匹配s
bool isMatch(string s, string p) {
// p為空時的討論
if (!p.length() && !s.length())
return true;
if (!p.length() && s.length() > 0)
return false;
// s為空時的討論,只有p為 .*.*.*.*.* 的形式時才能匹配
if (!s.length())
{
if (p.length() % 2 == 1) return false;
int i = 1;
while (i < p.length() && p[i] == '*')
{
i += 2;
}
if (i == p.length() + 1) return true;
else return false;
}
// p[1]為*時,用p+2匹配s+0,s+1,s+2,s+3…………,成功返回true,失敗返回false
int i = -1;
if (p.length() >=2 && p[1] == '*')
{
do {
// 當++i為len+1時截取字符串才會越界報錯,但是++i為len時截取的子串為空就已經返回結果了,所以永遠沒有機會截取len+1
if (isMatch(s.substr(++i), p.substr(2)))
return true;
// 匹配失敗且i已經為len了,即p+2匹配到s的最后了任然匹配失敗,return false
else if (i == s.length())
return false;
// 由於上面的++i截取到len時就會return退出,所以s[i]也永遠不會越界
} while ((s[i] == p[0] || p[0] == '.'));
return false;
}
// p[1]不為*時
else
{
if (s[0] == p[0] || p[0] == '.')
return isMatch(s.substr(1), p.substr(1));
else
return false;
}
}
};