【LeetCode】10. Regular Expression Matching
Regular Expression Matching
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). The function prototype should be: bool isMatch(const char *s, const char *p) Some examples: isMatch("aa","a") → false isMatch("aa","aa") → true isMatch("aaa","aa") → false isMatch("aa", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true
比较与Wildcard Matching的关系。
在Wildcard Matching中的'?'与此题的'.'一致。
但是Wildcard Matching中'*'本身代表通配符,而此题'*'代表前一个字符重复0或若干次。
解题过程如下:
1、考虑特殊情况即*s字符串或者*p字符串结束。
(1)*s字符串结束,要求*p也结束或者间隔‘*’ (例如*p="a*b*c*……"),否则无法匹配
(2)*s字符串未结束,而*p字符串结束,则无法匹配
2、*s字符串与*p字符串均未结束
(1)*(p+1)字符不为'*',则只需比较*s字符与*p字符,若相等则递归到*(s+1)字符串与*(p+1)字符串的比较,否则无法匹配。
(2)*(p+1)字符为'*',则*p字符可以匹配*s字符串中从0开始任意多(记为i)等于*p的字符,然后递归到*(s+i+1)字符串与*(p+2)字符串的比较,
只要匹配一种情况就算完全匹配。
class Solution { public: bool isMatch(const char *s, const char *p) { //entire match if(*s == 0) { if(*p == 0 || (*(p+1) == '*' && isMatch(s,p+2))) return true; else return false; } else if(*p == 0) return false; if(*(p+1) != '*') { if(*s == *p || *p == '.') return isMatch(s+1, p+1); else return false; } else { if(*s != *p && *p != '.') {//try matches 0 char, skip p and p+1 ('*') return isMatch(s, p+2); } else { //try matches 0 char, skip p and p+1 ('*') if(isMatch(s, p+2)) return true; int i = 0; while(*(s+i) == *p || *p == '.') {//try all the length '*' matches if(isMatch(s+i+1, p+2)) return true; if(*(s+i+1) == 0) //tried to end break; i ++; } return false; } } } };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架