static auto x = [ ] ( ) {
std :: ios :: sync_with_stdio ( false );
cin.tie ( NULL );
return 0;
}();
class Solution {
public:
bool isMatch(string s, string p) {
int m = s.length(), n = p.length();
return backtracking(s, m, p, n);
}
bool backtracking(string& s, int i, string& p, int j) {
if (i == 0 && j == 0) return true;
if (i != 0 && j == 0) return false;
if (i == 0 && j != 0) {
//in this case only p == "c*c*c*" this pattern can match null string
if (p[j-1] == '*') {
return backtracking(s, i, p, j-2);
}
return false;
}
//now both i and j are not null
if (s[i-1] == p[j-1] || p[j-1] == '.') {
return backtracking(s, i - 1, p, j - 1);
} else if (p[j-1] == '*') {
//two cases: determines on whether p[j-2] == s[i-1]
//first p[j-2]* matches zero characters of p
if (backtracking(s, i, p, j - 2)) return true;
//second consider whether p[j-2] == s[i-1], if true, then s[i-1] is matched, move to backtracking(i - 1, j)
if (p[j-2] == s[i-1] || p[j-2] == '.') {
return backtracking(s, i - 1, p, j);
}
return false;
}
return false;
}
};
LetCode 10. 正则表达式匹配
最新推荐文章于 2024-09-01 00:38:11 发布