LeetCode-010-正则表达式匹配
正则表达式匹配
题目描述:给你一个字符串 s 和一个字符规律 p,请你来实现一个支持 '.' 和 '*' 的正则表达式匹配。
'.' 匹配任意单个字符
'*' 匹配零个或多个前面的那一个元素
所谓匹配,是要涵盖 整个 字符串 s的,而不是部分字符串。示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/regular-expression-matching/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:遍历、递归
遍历p,将s和p进行匹配。分几种情况,分别是 '.' 或 '*' 或者两者都不是的情况, '.' 和两者都不是的相对比较简单,比较复杂点的是'**'的判断,因为'**'是匹配零个或多个元素,所以用到了递归。
public class Solution {
public static boolean isMatch(String s, String p) {
if ((s == null || s.length() == 0) && (p == null || p.length() == 0)) {
return true;
}
if ((p == null || p.length() == 0) && s.length() > 0) {
return false;
}
char preChar = 0;
boolean havePreChar = false;
int sIndex = 0;
for (int i = 0; i < p.length(); i++) {
if (p.charAt(i) == '.') {
if (i < p.length() - 1 && p.charAt(i + 1) == '*') {
preChar = p.charAt(i);
havePreChar = true;
continue;
} else {
if (sIndex < s.length()) {
preChar = s.charAt(sIndex);
sIndex++;
havePreChar = true;
continue;
} else {
return false;
}
}
}
if (p.charAt(i) == '*') {
if (!havePreChar) {
return false;
}
if (sIndex == s.length()) {
if (p.length() - 1 == i) {
return true;
} else {
return isMatch("", p.substring(i + 1));
}
} else {
if (preChar == '.') {
if (i == p.length() - 1) {
return true;
}
while (sIndex < s.length()) {
boolean result = isMatch(s.substring(sIndex), p.substring(i + 1));
if (result) {
return true;
}
sIndex++;
continue;
}
} else {
while (sIndex < s.length()) {
if (s.charAt(sIndex) == preChar) {
boolean result = isMatch(s.substring(sIndex), p.substring(i + 1));
if (result) {
return true;
}
sIndex++;
continue;
} else {
break;
}
}
}
havePreChar = false;
}
}
if (p.charAt(i) != '*' && p.charAt(i) != '.') {
if (i < p.length() - 1 && p.charAt(i + 1) == '*') {
preChar = p.charAt(i);
havePreChar = true;
continue;
} else {
if (sIndex == s.length() || s.charAt(sIndex) != p.charAt(i)) {
return false;
} else {
sIndex++;
havePreChar = false;
continue;
}
}
}
}
if (sIndex < s.length()) {
return false;
}
return true;
}
public static void main(String[] args) {
String s = "", p = "c*c*"; // true
System.out.println(isMatch(s, p));
}
}
分类:
LeetCode-个人题解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了