正则表达式匹配
给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
‘.’ 匹配任意单个字符
‘*’ 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s 的,而不是部分字符串。
https://leetcode.cn/problems/regular-expression-matching/
失败+写不出来的一天,明天看答案
class Solution {
public:
bool isMatch(string s, string p) {
int s_len = s.size(), p_len = p.size();
int idx_p = 0, i = 0;
while (i < s_len && idx_p < p_len) {
if (s[i] == p[idx_p]) {
i++;
idx_p++;
}
else {
if (p[idx_p] == '.') {
i++;
idx_p++;
}
else if (p[idx_p] == '*') {
char last_p = p[idx_p - 1];
if (last_p == '.') {
// 出现了.*的结构,直接开始找p=s的idx,直到找到终点
while (idx_p < p_len && i < s_len && p[idx_p] != s[i]) {
i++;
idx_p++;
}
}
else {
// 匹配0个 ,说明s的下一个字符不是p的上一个字符
if (s[i] != last_p) {
idx_p++;
}
else {
while (i < s_len && s[i] == last_p) {
i++;
}
idx_p++;
while (idx_p < p_len && p[idx_p] == last_p) {
idx_p++;
}
}
}
}
else if (idx_p + 1 < p_len && p[idx_p + 1] == '*') {
idx_p++;
}
else {
return false;
}
}
}
if (i == s_len && idx_p == p_len) {
return true;
}
return false;
}
};