JZ52 正则表达式匹配

本文最后更新于:2022年4月9日 中午

image-20211010151834648

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串
* @param pattern string字符串
* @return bool布尔型
*/
bool match(string str, string pattern) {
// write code here
return isMatch(str, 0, pattern, 0);
}

bool isMatch(const string& s, int i, const string& p, int j) {
if (j == p.size()) return i == s.size();
// 首字母匹配
bool first_match = (s.size() > i) && (p[j] == s[i] || p[j] == '.');
// 处理 '*',匹配 0 个或多个字符
if (p.size() >= j + 2 && p[j+1] == '*') {
return isMatch(s, i, p, j+2) || (first_match && isMatch(s, i+1, p, j));
}
// 处理 '.',匹配一个字符
return first_match && isMatch(s, i+1, p, j+1);
}
};

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!