第十四周:[LeetCode]10. Regular Expression Matching

★leetcode10_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 ent 阅读详情

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


分情况用递归解决。
首先便携式一个函数判断s和p当前字符匹配是否匹配:若字符相同或p为’.’,则”s和p当前字符匹配”。
1、若p为空,若s也为空,返回true,反之返回false;
2、若p的长度为1,若s长度也为1,且”s和p当前字符匹配”,则返回true,反之返回false;
3、若p的第二个字符不为’*’,若此时s为空返回false,否则若”s和p当前字符匹配”,再从各自的第二个字符开始调用递归函数匹配;
4、若p的第二个字符为’*’,若”s和p当前字符匹配”,调用递归函数匹配s和去掉前两个字符的p,若匹配返回true,否则s去掉首字母继续上述匹配过程;
5、返回调用递归函数匹配s和去掉前两个字符的p的结果;


bool SMatchP(char s,char p){
    return s == p || p == '.';
}

bool isMatch(string s, string p) {
    if(p.empty())
        return s.empty();
    if(p.size() == 1)
        return (s.size() == 1 && SMatchP(s[0],p[0]));
    if(p[1] != '*'){
        if(s.empty())
            return false;
        return SMatchP(s[0],p[0]) && isMatch(s.substr(1), p.substr(1));
    }
    while (!s.empty() && SMatchP(s[0],p[0])) {
        if(isMatch(s,p.substr(2)))
            return true;
        s = s.substr(1);
    }
    return isMatch(s, p.substr(2));
}
用MATLAB从零实现六足机器人步态仿真:交替三角与波动步态保姆级教程 本文详细介绍了如何使用MATLAB从零实现六足机器人的两种经典步态仿真:交替三角支撑步态和波动步态。通过参数定义、相位设置、运动轨迹生成和三维可视化等步骤,帮助读者掌握六足机器人步态规划的核心技术。教程包含完整代码和详细解析,适合机器人爱好者和相关专业学生学习实践。 阅读详情

相关推荐

【hadoop编译报错】(yarn install) on project hadoop-yarn-applications-catalog-webapp Failed to run task

ambari+bigtop自定义组件集成

TTBIGDATA的博客 1810

leetcode第10题——***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

buptlrw的专栏 2605

从零开始:使用VMOS Pro和Xposed绕过APP环境检测的完整指南

本文详细解析了使用VMOS Pro和Xposed框架绕过APP环境检测的完整技术方案,包括模拟器检测、Root环境检测和Hook框架检测的对抗方法。通过实战案例和代码示例,展示了如何利用Xposed Hook技术拦截检测逻辑,特别针对360加固等保护技术提供了解决方案。

ee345的博客 744

leetcode题解:第10题Regular Expression Matching

https://leetcode-cn.com/problems/regular-expression-matching/ 分析 这道题的难点在于存在a*这样的组合,如何处理与这种组合匹配的字符数是很棘手的问题,例如: s = "aaa", p = "aa*" s = "baaa", p = "ba*" 第一个例子中a*匹配2个字符,第二个例子中a*匹配3个字符。可以看出,匹配的字符数不仅与s有关,还与p中组合前面的字符有关(后面也有可能)。如果是.*这样的组合,会更加麻烦。 我一开始的想法是用双指针分别

chenf1999的博客 313

高杂合度基因组组装实战:Hifiasm参数调优与purge_dups过滤效果对比(附猪毛菜案例)

本文深入探讨了高杂合度基因组组装中Hifiasm参数调优与purge_dups过滤的实战效果对比,通过猪毛菜案例详细解析了两种方法的适用场景与优化策略。文章重点分析了purge_dups在contig过滤中的显著效果,为基因组组装提供了关键的技术参考。

weixin_29232121的博客 504

华中科技大学 计算机组成原理 educoder Logisim平台 计算机数据表示实验

本文主要是对 计算机数据表示实验的笔记和相关Logisim平台的图,供大家学习交流使用。 需要源文件或者源代码,可以留言评论! 目录实验目的第1关:汉字国标码转区位码实验第2关:汉字机内码获取实验第3关:偶校验编码设计第4关:偶校验解码电路设计第5关:16位海明编码电路设计第6关:16位海明解码电路设计第7关:海明编码流水传输实验第8关:16位CRC并行编解码电路设计第9关:CRC编码流水传输实验实验结果: 实验目的 本实训将帮助同学们巩固对计算机中数据表示方法的理解,要求能设计汉字国标码与区位码之间的转换

weixin_48383580的博客 2万+

Leetcode: 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 st

ZkvIA的博客 2万+

NXP S32K1 SPI驱动实战:从配置到DMA传输的完整流程解析

本文深入解析了NXP S32K1系列MCU的SPI驱动开发全流程。基于S32 Design Studio环境,详细阐述了从引脚配置、LPSPI模块初始化,到实现阻塞、中断及DMA三种传输模式的实战代码与配置要点。文章重点剖析了DMA传输的配置细节与性能优化,旨在帮助开发者构建高效、稳定的嵌入式SPI通信,并提供了SPI Flash驱动的综合案例。

blue42的博客 730

leetcode 10: Regular Expression Matching

Regular Expression Matching Total Accepted: 39732 Total Submissions: 192279 Implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Mat

西施豆腐渣 2806

高可用架构设计——多节点OpenClaw集群部署与负载均衡(2026企业级)

本文介绍了企业级OpenClaw高可用集群架构设计,重点阐述了多节点部署与负载均衡方案。架构采用分层设计,包括表现层、应用层、数据层和基础设施层,确保99.99%的可用性目标。详细配置了主节点、工作节点和存储节点规格,提供Kubernetes集群部署脚本示例,实现自动化的容器编排管理。通过硬件冗余、故障隔离和弹性扩展等可靠性原则,构建能够应对各种故障场景的稳定AI助手系统。

博客 428

10、使用Ray Serve实现微服务与模型部署

本文深入介绍了如何使用Ray Serve实现微服务与机器学习模型的高效部署。从基础的部署定义到复杂的模型服务场景,涵盖部署架构、HTTP与Python调用、资源配置、FastAPI集成、金丝雀发布策略及实际应用流程。文章还探讨了模型服务的关键需求如灵活性、批处理、硬件优化和可扩展性,并展示了Ray Serve如何满足这些要求。最后提供了常见问题解决方案与未来发展方向,帮助开发者构建高性能、易维护的模型服务平台。

blue42的博客 182

【Leetcode】10. Regular Expression Matching

考虑初始条件,空字符串可以和空模式匹配,而非空字符串无法和空模式匹配,所以。不合法,我们也应该返回false。一下子是看不出来的,需要在递推的过程中算出来。,只是为了将不合法的情形包含进去);出现,也就是那个整体匹配的一部分是。末字符匹配完之后,前面有可能还有。是个合法的模式串,应该有如果。如果这个整体按照出现大于等于。,这个整体匹配完之后,还需要。,因为那个整体是匹配大于等于。可以匹配其之前的字符重复。次来匹配,那么就要求或者。可以匹配任何单个字符,次来匹配,那么结果就是。如果这个整体按照出现。

数学、算法爱好者的博客 359

深度解读华为Limera:从舱内激光视觉融合看前融合技术的发展与演进

华为Limera激光雷达摄像头融合技术推动自动驾驶感知升级 华为推出的Limera创新性地将激光雷达与摄像头深度集成,采用共光路设计实现数据天然对齐,在小型障碍物识别等关键场景展现卓越性能。该产品代表了传感器前融合技术从分立走向共生的演进趋势,通过硬件级集成解决了多源异构数据融合难题。随着索尼堆叠式传感器等技术的出现,未来智能汽车感知系统将向高度集成的"超级传感器"方向发展,实现更精准的环境感知。Limera的发布标志着前融合技术从"可用"迈向"极致&quo

致力于lidar应用开发 409

【LeetCode】10.Regular Expression Matching(Python)

Problem LeetCode 10: 正则表达式匹配 难度:hard 给定输入字符串和模式(P),实现与“.”和“”支持匹配的正则表达式。 “.”匹配任何单个字符。 “”与前面的单个元素零个或多个匹配。 匹配应该覆盖整个输入字符串(而不是部分)。 注: s可以为空,并且只包含小写字母a-z。 p可以为空,只包含小写字母a-z和类似的字符。或者*。 例1: 输入:S=“AA”, P=“A” 输出...

E.W的博客 1450

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

leetcode 第10题 Regular Expression Matching

周末也没有做leetcode,感觉有点罪恶啊,这个第10题好难啊,涉及到递归了,看的我是头晕眼花啊。我看着看着还是有点收获的,我发现题目仍然没有我想象中的那么的简单,如果s = 'a b c d e',p = '. * e',这样匹配出的结果也是正确的,我就很纳闷儿啊,' . '是匹配任意一个字符,可是我以为只能匹配一个字符,但是从这个算例上看,当它和' * '在一起时,' . '可以多次匹配不同

paofuhemakalong的博客 989

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

LeetCode(Regular Expression Matching & Wildcard Matching)

【代码】LeetCode(Regular Expression Matching & Wildcard Matching)

Jiajun Zhu 278

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

leetcode10 Regular Expression Matching @python

leetcode里一道hard难度的题(第10题), 题主已经栽死在里面,借鉴了别人优秀的思想用python实现了,经典的东西要保留。 感谢@Vosky

nadizhong4136的博客 409

10. Regular Expression Matching 正则表达式匹配

题目:Regular Expression Matching 正则表达式匹配 难度:困难 Given an input string (s) and a pattern (p), implement regular expression matching with support for'.'and'*'. '.' Matches any single character. '*' ...

qq_21963133的博客 551

[LeetCode]Regular Expression Matching、Wildcard 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 matchin

a83610312的专栏 5756

LeetCode 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

Coding for Dreams 2600

leetcode 10: Regular Expression Matching 分析及解答

解读: •‘.'代表一个任意字符,与其附近的字符无关 •’*‘代表o个或者多个前面的字符,该字符影响前面字符的“存在”,例如:a*={ε,a,aa,aaa,…},即当"*"表示0个前面的字符时,该字符串为空串ε。 分析:题目要求匹配整个输入字符串,即完全匹配,分如下情况: 1.同时为空则true p为ε时,s为ε则匹配 s为ε时,p为ε则匹配,但此时p分两种情况: 1、p确实为ε 2、p为”a*“类型,此时*代表前面的字符存在0次,则p在匹配意义上位ε 2.不同时为空就需要比较 •p字符串中当前字

若有所思HS 1736

【todo+低频题】LeetCode 10. Regular Expression Matching

LeetCode 10. Regular Expression Matching 本博客参考:http://www.cnblogs.com/grandyang/p/4461713.html 详细解析见另一题:【重点】剑指offer——面试题53:正则表达式匹配里面的代码风格是C的,现在把它改成C++风格的代码。在剑指offer53题的代码中,由于代码风格的原因,未考虑p.size() == 1...

Allenlzcoder的博客 1302

LeetCode 10: 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 inpu

哈哈的个人专栏 2717

【leetcode】10. Regular Expression Matching

Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'. '.' Matches any single character. '*' Matches zero or more of the preceding element. ...

ghscarecrow的博客 564

leetcode 10 Regular Expression Matching

题目地址及大意 回溯法 动态规划方法 题目地址及大意题目leetcode 10 Regular Expression Matching大意如下:给定两个字符串,s 与 p,其中 p 有可能包含 . 和 * 两种元素。其中, . 可以代表任何一个字符, * 代表它前面的字符重复 0 次或者更多次。 即 a* 可以代表 空字符, 只含有一个a,含有两个a……题目刚开始看的时候我连题意都没有很理解,以

Alice lr的博客 391

LeetCode 10. Regular Expression Matching

LeetCode 10. Regular Expression MatchingDescriptionNoteExampleCodeConclusion Description Given an input string (s) and a pattern (p), implement regular expression matching with support for'.'and'*'. ...

gq__97的博客 237
上一篇: 第十三周:[Sicily]1423. 魔王bug的2色定理
下一篇: 第十五周:[Sicily]1504. Slim Span
line02
博客等级 码龄15年 3粉丝 45原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值