leetcode算法每天一题010: 正则表达式匹配(递归)

该文章介绍了一个C++实现的字符串匹配算法,主要关注如何处理通配符*的情况。算法通过递归地比较字符串`s`和模式`p`中的字符,处理*作为0个或多个前面字符的重复。当遇到*时,会尝试跳过或者继续匹配多个字符来找到正确的匹配方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 每次从p中拿出一个字符来与s中的字符进行匹配
  • 如果该字符后续的字符不是*,那么直接与s中对应字符进行匹配判断即可, 如果匹配上了,那么就将两个游标都往后移动一位。
  • 如果后续字符是*,分成两种独立的情况,两种情况有一个能正确匹配即可
    1.一种是匹配0个,那么只需要跳过p中的这两个字符( p=p.substr(2) ),继续与s中的字符进行比较即可,2.如果是匹配多个,那么将s中的游标往后移动一个,继续进行判断,
#include <stdio.h>
#include<vector>
#include<memory>
#include<iostream>
using namespace std;
class Solution {
public:
#include <stdio.h>
#include<vector>
#include<memory>
#include<iostream>
using namespace std;
class Solution {
public:
    bool isMatch(string s, string p) {
        if (p.empty()) return s.empty();
        
        auto first_match = !s.empty() && (s[0] == p[0] || p[0] == '.');
        
        if (p.size() >= 2 && p[1] == '*') {
            bool jump = isMatch(s, p.substr(2));//跳过的情况,第一个字符可以不匹配
            bool godown = first_match && isMatch(s.substr(1), p)
            return  jump || godown ;
        } else {
            return first_match && isMatch(s.substr(1), p.substr(1));//pos的默认值是0,len的默认值是s.size() - pos
        }
    }
};
int main()
{
    printf("--->");
    unique_ptr<Solution> mysolo = unique_ptr<Solution>(new Solution());
	string s="aa"; string p="a*";
	int res = mysolo->isMatch(s,p);
	cout<< res<< endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值