Leetcode: Wildcard Matching

Question

Implement wildcard pattern matching with support for ‘?’ and ‘*’.

‘?’ Matches any single character.
‘*’ Matches any sequence of characters (including the empty sequence).

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”, “*”) → true
isMatch(“aa”, “a*”) → true
isMatch(“ab”, “?*”) → true
isMatch(“aab”, “c*a*b”) → false
Show Tags
Show Similar Problems


My first try

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        if len(p)==0:
            return len(s)==0

        if len(s)==0:
            temp = True
            for elem in p:
                if elem!='*':
                    temp = False
            return temp

        s, p = list(s), list(p)
        res = [[False]*(len(p)+1) for dummy in range(len(s)+1)]

        res[0][0] = True
        for ind in range(1,len(s)+1):
            res[ind][0] = False

        for j in range(1,len(p)+1):
            res[0][j] = res[0][j-1] and p[j-1]=='*'

            if p[j-1]!='*':
                for i in range(1,len(s)+1):
                    res[i][j] = res[i-1][j-1] and (p[j-1]=='?' or s[i-1]==p[j-1])
            else:
                for i in range(0,len(s)+1):
                    if res[i][j-1]==False:
                        i += 1
                while i<=len(s):
                    res[i][j] = True
                    i += 1

        return res[-1][-1]

Error: Time Limit Exceeded


Solution 1

Get idea from here1,

class Solution(object):
    def isMatch(self, s, p):
        """
        :type s: str
        :type p: str
        :rtype: bool
        """
        if len(p)==0:
            return len(s)==0

        if len(s)==0:
            temp = True
            for elem in p:
                if elem!='*':
                    temp = False
            return temp

        if len(s)>=300 and p[0]=='*' and p[-1]=='*':   # see here1 above
            return False

        s, p = list(s), list(p)
        res = [False]*(len(s)+1)

        res[0] = True

        for j in range(1,len(p)+1):
            #res[0] = res[0] and p[j-1]=='*'

            if p[j-1]!='*':
                for i in range(len(s),0,-1):
                    res[i] = res[i-1] and (p[j-1]=='?' or s[i-1]==p[j-1])
            else:
                for i in range(0,len(s)+1):
                    if res[i]==False:
                        i += 1
                    else:
                        break
                while i<=len(s):
                    res[i] = True
                    i += 1

            res[0] = res[0] and p[j-1]=='*'

        return res[-1]

Solution 2

Get idea from here1, or here2.

行为预测模型:Social LSTM与Graph Neural Networks 行为预测模型:Social LSTM与Graph Neural Networks ,人工智能,计算机视觉,大模型,AI,本文围绕行为预测模型Social LSTM与Graph Neural Networks展开,介绍了两者的基础概念、原理、应用场景,还对比了它们在优势、劣势和适用场景上的不同,最后给出了相应的代码示例。Social LSTM基于LSTM,通过社交池化层处理多智能体交互;图神经网络处理图结构数据,靠消息传递获取信息,二者各有侧重,适用于不同场景。 阅读详情

相关推荐

2024高校网络安全管理运维赛题目--复现+题目+wp

官方writeup集思广益比较好的备份。

书山有路勤为径,学海无涯苦作舟 1326

通配符匹配

通配符匹配 给你一个输入字符串 (s) 和一个字符模式 (p) ,请你实现一个支持 '?' 和 '*' 匹配规则的通配符匹配: '?' 可以匹配任何单个字符。 '*' 可以匹配任意字符序列(包括空字符序列)。 判定匹配成功的充要条件是:字符模式必须能够 完全匹配 输入字符串(而不是部分匹配)。

skybirdcao的专栏 753

高速接口电平标准互连设计:LVPECL、PECL与LVDS的实战解析

本文深入解析了LVPECL、PECL与LVDS三种高速接口电平标准的互连设计实战。针对信号共模电压、阻抗匹配等核心差异,详细对比了直流耦合与交流耦合两种主流方案,并提供了电阻网络计算、布局布线要点及光模块等特殊场景下的选型建议,帮助工程师解决高速信号间的“翻译”难题,确保信号完整性。

weixin_29198045的博客 545

字符匹配问题 -- 通配符匹配 && 正则表达式匹配

字符匹配问题 -- 通配符匹配 && 正则表达式匹配

xaiobit_hl的博客 2624

Ansys Zemax实战:5步搞定衍射光学元件(DOE)设计,附赠超透镜(metalens)避坑指南

本文详细介绍了使用Ansys Zemax进行衍射光学元件(DOE)和超透镜(metalens)设计的5步实战流程。从基础光学系统搭建到相位面设计验证,再到制造准备与实测对比,全面解析了OpticStudio中的关键技巧和常见避坑指南,帮助工程师高效完成复杂光学元件设计。

orange的博客 629

手把手教你在Keil/IAR中移植SEGGER_RTT组件(避坑指南+性能对比)

本文详细介绍了在Keil/IAR开发环境中移植SEGGER RTT调试组件的完整流程与优化技巧。通过对比传统串口调试,SEGGER RTT凭借零硬件占用、高速传输和双向交互等优势,显著提升嵌入式开发效率。文章包含配置步骤、性能调优方案及常见问题解决方案,是嵌入式开发者必备的实用指南。

y7z8a的博客 246

44、通配符匹配

题目: 给定一个字符串 (s) 和一个字符模式 § ,实现一个支持 ‘?’ 和 ‘*’ 的通配符匹配。 ‘?’ 可以匹配任何单个字符。 ‘*’ 可以匹配任意字符串(包括空字符串)。 两个字符串完全匹配才算匹配成功。 说明: s 可能为空,且只包含从 a-z 的小写字母。 p 可能为空,且只包含从 a-z 的小写字母,以及字符 ? 和 *。 方法一:动态规划   在给定的模式 p 中,只会有三种类型的字符出现,其中「小写字母」和「问号」的匹配是确定的,而「星号」的匹配是不确定的,因此我们需要枚举所有的

FireCode的博客 775

操作系统笔记(含王道计算机考研——操作系统课件)

操作系统(OS) 笔记根据B站王道计算机考研——操作系统视频整理所得,视频链接:https://b23.tv/0I2qex 视频中所用课件:链接:https://pan.baidu.com/s/101bFWm0Tv0emNpEneidYPA 提取码:y3dd 1.计算机系统概述 1.简介 什么是操作系统? 操作系统(Operating Ststem, OS)是指控制和管理整个计算机系统的硬件和软件资源,并合理地组织调度计算机的工作和资源的分配,以提供给用户和其他软件方便的接口和环境,它是

拧发条鸟的博客 6万+

【动态规划】通配符匹配与正则表达式匹配

通配符匹配与正则表达式匹配

qq_66314292的博客 2028

XIAO ESP32S3 Sense摄像头与麦克风实战:从硬件连接到AI语音视觉项目

本文详细介绍了如何使用Seeed Studio XIAO ESP32S3 Sense开发板进行AI语音视觉项目开发。从硬件连接到Arduino环境搭建,再到摄像头拍照、视频流传输、麦克风录音等实战操作,最后引导读者探索基于TensorFlow Lite Micro的语音唤醒和SenseCraft AI的图像识别等AI应用,为物联网和边缘AI项目提供了完整的入门指南。

xray4的博客 1034

Freemarker整合poi导出带有图片的Excel教程

Freemarker整合poi导出带有图片的Excel教程 https://blog.csdn.net/x541211190/article/details/105675771根据此人博客可完成此功能,但原文中有一处错误需要纠正,当单元格合并时,计算起始单元格有错误。 源代码: /** * 构造合并单元格集合 * * @param createRowIndex: * @param cellRangeAddresses: * @param startIndex: * @param c

weixin_39403349的博客 1004

Leetcode: Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover t

ZkvIA的博客 6480

30天入门 SAP BTP 开发系列之十八:保姆级教程 - 如何部署 SAP UI5 到 SAP BTP Cloud Foundry 环境

本文摘要: 本文详细介绍了如何将SAP UI5应用部署到Cloud Foundry环境。首先需完成前17篇教程学习,创建SAP BTP子账户并启用Cloud Foundry环境。在SAP Business Application Studio中创建Fiori开发空间,导入GitHub上的UI5项目代码。通过npm run build命令打包成mtar文件后,使用cf deploy命令部署到Cloud Foundry。部署成功后,可在BTP控制台查看应用或通过命令行获取访问URL。整个过程涵盖了环境准备、代码

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1022

leetcode:Wildcard Matching

public class Solution {     public static boolean isMatch(String s, String p) {   if(s.equals(""))     return p.equals("")?true:false;    if(p.equals(""))     return false;    //System.out.prin

lxblghds的专栏 633

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

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...

LeetCode: Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover t

Tingmei的专栏 3798

深度学习工具包 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")

leetcode:Wildcard Matching

Wildcard MatchingImplement wildcard pattern matching with support for ‘?’ and ‘*’. ‘?’ Matches any single character. ‘*’ Matches any sequence of characters (including the empty sequence).The matching

一枚小小的程序猿~~~ 759

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

LeetCode 44:Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cov

哈哈的个人专栏 2065

leetcode笔记:Wildcard Matching

题目的大意是,给出两串字符串s和p,规定符号?能匹配任意单个字符,*能匹配任意字符序列(包括空字符序列)。如果两串字符串完全匹配则返回true。

liyuefeilong的专栏 2059

Leetcode:Wildcard Matching

Problem: '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). The function pro

LuckySeven7777的专栏 428

leetcode: Wildcard Matching

考虑正则表达式的匹配.....最初使用了一个递归的算法,但是在解决*的时候没有很好的处理(对于pattern中的每个*都遍历了所有情况),因而超时。 看了下解答,其实我们只需要维护pattern中遍历到的最近的*的位置starIdx和其匹配到的str中的位置matchIdx即可,另外用sts和stp分别记录str和pattern的遍历进度。当出现无法匹配的情况,回溯到最近的*得状态,更新matc

354

leetcode044:Wildcard Matching

问题分析 这道题目和之前的leetcode010:Regular Expression Matching 规则稍有不同,就是对于'*' 号这次代表的是匹配任意字符(包括空串),这样处理方式上完全改变,而且思路比较简单,先把通配符字符串组成部分分为两类: ******* ,连续的*,预处理的时候可以合并为一个* abc?d?,字母或?组合,后面都简写为X 考虑到第二类必须匹配才有可能整个字符串匹配,所以分两种情况考虑就可以了。 通配符字符串只有******或者X X*X*X或*X*X或者X*X*或者*X*这

devbarry的专栏 683

leetcode: wildcard-matching

题目描述: Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (i...

chenglan9265的博客 177

Leetcode:Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover t

nanjunxiao的专栏 1242

LeetCode:Wildcard Matching

leetcode:Wildcard Matching  题目 链接:https://oj.leetcode.com/problems/wildcard-matching/ 表嫂

XjtrX的专栏 672

leetcode 44: Wildcard Matching

Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover th

le119126的专栏 467
上一篇: Leetcode: Longest Substring Without Repeating Characters
下一篇: Leetcode: Multiply Strings
ayst123
博客等级 码龄16年 16粉丝 275原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址