LeetCode 44. Wildcard Matching--动态规划

LeetCode 44. Wildcard Matching(模糊匹配) 原题网址:https://leetcode.com/problems/wildcard-matching/ Implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters ( 阅读详情

题目链接

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 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
解:果然是字符串的问题都可以用dp来解,dp[i][j]代表的含义是s前i个字符的子串和p的前j个字符的子串是否匹配,如果是dp[0][j]那么代表空串和非空串的匹配,“”和“”或连续的‘*’可以匹配。
dp状态转移:
1)s[i-1] == '*'  => dp[i-1][0]...dp[i-1][j]中有一个为true,dp[i][j] = true
2)p[j-1] == '*'  => dp[0][j-1]...dp[i][j-1]中一个为true,dp[i][j] = true
3)s[i-1] 同 p[j-1]字符相匹配,'?'或者其他的相同字符  => dp[i][j] = dp[i-1][j-1]
4) s[i-1] 同 p[j-1]字符不匹配  => dp[i][j] = false
代码:
class Solution {
public:
    bool isMatch(string s, string p) {
        int size_s = s.length();
        int size_p = p.length();
        vector<vector<bool> > dp(size_s+1, vector<bool>(size_p+1, false));
        dp[0][0] = true;
        for (int i = 1; i <= size_s; i++) dp[i][0] = s[i-1] == '*' && dp[i-1][0] ? true : false;
        for (int i = 1; i <= size_p; i++) dp[0][i] = p[i-1] == '*' && dp[0][i-1] ? true : false;
        for (int i = 1; i <= size_s; i++) {
            for (int j = 1; j <= size_p; j++) {
                if (s[i-1] == '*') {
                    for (int t = 0; t <= j; t++) dp[i][j] = dp[i][j] || dp[i-1][t];
                }
                if (p[j-1] == '*') {
                    for (int t = 0; t <= i; t++) {
                     	dp[i][j] = dp[i][j] || dp[t][j-1];
                    }
                    continue;
                }
                if(s[i-1] == '?' || p[j-1] == '?' || s[i-1] == p[j-1]) dp[i][j] = dp[i][j] || dp[i-1][j-1];
                else dp[i][j] = false;
            }
        }
        return dp[size_s][size_p];
    }
};



Leetcode #44. Wildcard Matching 通配符匹配 解题报告 1 解题思想嗯,最近遇到要写Hard的频率偏高,而最近的重心也不再Leetcode上,心累。。Hard写起来都好麻烦。这道题好像之前也有几次,讲过类似的题目,也就是*能任意长度和字符匹配,?能匹配任意一个字符,现在需要验证给定的通配符是否能匹配输入的串这道题应该有很多做法,我的这个感觉只是一个比较一般的解法,这道题的测试量比较大,所以单纯的暴力搜索是AC不掉的,而我的做法,就是使用动态规划。不知道大 阅读详情

相关推荐

Leetcode | C++ 44-Wildcard Matching

题目分析: 给你s和p两个字符串,它们均由小写字母以及’?’、’*‘组成,其中’?‘与任何一个字符匹配,’*'与任何长度字符串匹配(可以为空),问s和p是否完全匹配。 解题思路(1): 很容易想到dfs的方法,用dfs(i,j)表示当前要当前检查到s[i]与p[j],如果两个都不是’*’,那么直接看这两个字母是否匹配,如果匹配继续往下走dfs(i+1,j+1),否则返回false;如果s[i]与p[j]中有’*’,比如s[i]=’*’,那么dfs(i+1,j)、dfs(i+1,j+1)……dfs(i+1,l

weixin_54707168的博客 340

【LeetCode】Wildcard Matching 串匹配 动态规划

题目:Wildcard Matching /*LeetCode WildCard matching * 题目:给定一个目标串和一个匹配串,判定是否能够匹配 * 匹配串中的定义:字符————>字符,*————>0个、1个或者多个字符,?——————>对应任意一个字符 * 思路:动态规划:*:dp[i][j] = dp[i][j-1] || dp[i-1][j] * ? || s[i

HIT_微笑前进的专栏 2581

从零到一:MIPI D-PHY测试环境的搭建与优化实战指南

本文详细介绍了MIPI D-PHY测试环境的搭建与优化实战指南,涵盖核心设备选型、测试点选取、接地屏蔽技巧、校准流程及自动化测试方案。特别针对D-PHY协议中的关键测试项进行深度解析,并提供疑难问题排查与性能优化建议,帮助硬件工程师高效完成高速差分信号测试。

lll78的博客 637

String、动态规划——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 the

jingsuwen1的博客 1201

STLink驱动故障全解析:从卡顿到重装的终极修复指南

本文全面解析STLink驱动故障的常见现象及解决方案,包括驱动卸载、重装、Keil环境配置等关键步骤。针对设备管理器黄色感叹号、Keil识别异常等问题,提供从软件到硬件的终极修复指南,帮助开发者高效解决STLink连接问题。

sss66的博客 741

2026 最新实战教程:AI 重构开发全流程(从需求→上线→运维)

1)做什么系统2)技术栈3)功能模块4)部署要求plaintext我要做一个:待办事项(Todo)全栈应用技术栈:前端:React + TypeScript + Tailwind后端:Node.js + Express + MongoDB部署:Docker + 本地运行(后续可上云)功能:- 增删改查任务- 任务状态切换(完成/未完成)- 简单错误处理请按企业级标准生成:架构设计 + 全部代码 + 接口文档 + 启动命令。

qq_35779316的博客 1771

Wildcard Matching -- LeetCode

原题链接:http://oj.leetcode.com/problems/wildcard-matching/这道题目其实是Regular Expression Matching的简化版,在这里'?'相当于那边的'.',而'*'相当于那边的'.*',因为这里'*'就可以代替任何字符串,不需要看前面的字符,所以处理起来更加简单。brute force的方法就不重新列举代码了,有兴趣实现的朋友可以...

编程语言小筑 251

Claude Code+Cursor+Claude 4三剑合璧!5步搞定Magentic-UI的OAuth2.0集成,开发效率飙升500%,新手秒变全栈工程师

本文详细介绍了如何利用Claude Code、Cursor和Claude 4三款AI工具高效集成Magentic-UI的OAuth2.0认证系统。通过5个步骤的实战演练,开发者可快速完成从环境搭建、项目分析、代码生成到前端集成的全过程,显著提升开发效率。文章还提供了JWT令牌管理、安全配置及常见问题解决方案。

weixin_29234509的博客 462

【LeetCode】44. Wildcard Matching 解题报告(Python)

题目分析: 这个题又是做类似正则匹配的,和【LeetCode】10. Regular Expression Matching基本一致。我们采用动态规划解决,创建状态数组dp然后分别判断是*怎么处理,或者是?怎么处理,详见测试代码。 测试代码: class Solution: def isMatch(self, s, p): m, n = len(s), len(p) ...

L141210113的专栏 1858

【电磁场计算】磁偶极子在外磁场中的受力

最近在总结电磁场计算公式的时候发现,关于磁偶极子受力的计算公式,在不同文献中的说明有点出入,在此特地写一篇博客澄清一下。

sky4403的博客 7490

【项目管理】第8章 项目整合管理 --知识点整理

制定项目章程: 第一步,旨在明确项目的目标、范围、关键里程碑等关键信息,为项目的后续工作奠定基础。制订项目管理计划: 在项目章程的基础上,进一步详细规划项目的执行过程,包括时间、成本、质量、风险等方面的管理计划。指导与管理项目执行: 按照项目管理计划执行项目,同时监控项目的进展,确保项目按照计划进行。监控项目工作: 对项目的执行情况进行持续监控,及时发现并解决问题,确保项目目标的实现。

weixin_42081167的博客 1603

[Leetcode][Python]44:Wildcard Matching

# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'44:Wildcard Matchinghttps://oj.leetcode.com/problems/wildcard-matching/'?' Matches any single character.'*' Matches any sequence of cha...

aaron7909的博客 219

【OpenCV】第二十三章: 图像特征检测之SURF、FAST、BRIEF、OBR算法

4、由于在检测特征点时是需要对图像中所有的像素点进行检测,然而图像中的绝大多数点都不是特征点,如果对每个像素点都进行上述的检测过程,那显然是种浪费,所以FAST采用一种进行非特征点判别的方法:首先对候选点的周围90度的点(1,9,5,13)四个点进行测试,而且是先测试1和9,如果它们两个符合阈值要求再测试5和13。继SIFT和SURF后,大家在特征点检测的速度上又进行了很多的改进尝试,但速度的提升效果都不是非常明显,直到FAST算法诞生,特征点检测的速度才有了一个质的飞跃。无法计算描述符的特征点将被删除。

因为热爱所以坚持 2163

LeetCode 44. Wildcard Matching动态规划算法实现

题目内容 Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. 两个字符串,S作为被匹配的字符串,P作为匹配字符串 '?' Matches any single character. '*' Matches any sequ...

太玄经的博客 403

Android SystemUI——初始化流程(三)

1、Android 系统在启动之后,首先会Zygote进程,Zygote进程又会进一步启动 SystemServer进程,它会启动各种系统所需要的服务,在监听AMS启动完毕之后,还会启动SystemUIService。2、在启动SystemUIService服务之前,系统首先会创建SystemUI对应的进程,获取SystemUIAppComponentFactory实例对象,调用instantiateApplicationCompat创建SystemUIApplication实例对象并设置回调方法。

小旭的专栏 1168

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

算法学习之动态规划(leetcode 44 Wildcard Matching)

Wildcard Matching

maxiaotiaoti的专栏 990

深度学习工具包 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 44 Wildcard Matching

problem:https://leetcode.com/problems/wildcard-matching/ 用记忆化搜索做的,不容易出错: class Solution { public: vector<vector<int>> dp; bool isMatch(const string& s, cons...

ayzejx8547408的博客 116

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

【LeetCode】解题44:Wildcard Matching(动态规划解法)

LeetCode解题 44:Wildcard Matching(动态规划解法)Problem 44: Wildcard Matching [Hard]解题思路Solution (Java) Problem 44: Wildcard Matching [Hard] Given an input string (s) and a pattern (p), implement wildcard patt...

Fayedily的博客 435

Leetcode 44. Wildcard Matching (动态规划解法)

题目: Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for'?'and'*'. '?' Matches any single character. '*' Matches any sequence of characters (includin...

Lin_QC的博客 321

LeetCode 44. Wildcard Matching (DP动态规划) C++

Given an input string (s) and a pattern §, 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 inpu

ganlanA的博客 274

LeetCode C++ 44. Wildcard Matching【动态规划/回溯】困难

Given an input string (s) and a pattern (p), 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 i

memcpy0的博客 611

模糊匹配 -- 关于暴力与动态规划的思考 Leetcode 44. Wildcard Matching

0x00 题目 Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence ...

维纳斯的迷图 407

LeetCode44,Hard,从搜索到动态规划的详细推导

本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题的第24篇文章,我们一起来看LeetCode的44题——Wildcard Matching,这是一道Hard难度的问题,会稍稍有点难,但是好消息是没有出现我们之前没见过的算法。 题意很简单,给定两个字符串s和p,其中s是母串,p是模式串。简单解释一下这两个概念,这两个概念一般出现在字符串匹配的问题当中。有些同学...

TechFlow的博客 365

【To Understand! 重点 递归 动态规划 正则表达式匹配】LeetCode 44. Wildcard Matching

LeetCode 44. Wildcard Matching Solution1:我的答案 递归,时间复杂度是O(2n)O(2n)O(2^n)因为超时未能AC 只是记录一下,以警示后人…… class Solution { public: bool isMatch(string s, string p) { if (p.size() == 0) return s.e...

Allenlzcoder的博客 295

【面试题 & LeetCode 44】Wildcard Matching

题目描述 Given an input string (s) and a pattern §, implement wildcard pattern matching with support for ‘?’ and ‘*’. ‘?’ Matches any single character. ‘*’ Matches any sequence of characters (including th...

iCode_girl的博客 219

LeetCode - 44 - Wildcard Matching(模式串匹配2

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

j6635788的博客 355
上一篇: LeetCode 207. Course Schedule--Graph
下一篇: 蓝桥杯 方格填数
monkey_rose
博客等级 码龄10年 9粉丝 55原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值