Leetcode: Word Break

〔重庆理工大学〕大学物理实验--变温霍耳效应及其参数测定 每个老师要求不同,实验报告内容和数据仅供参考。 阅读详情

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

For example, given

s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".


第一种方法:递归(超时)Time Limit Exceeded

思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配

Last executed input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", ["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]


bool wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once.
        if(s.length() < 1) return true;
		bool flag = false;
		for(int i = 1; i <= s.length(); i++)
		{
			string tmpstr = s.substr(0,i);
			unordered_set<string>::iterator it = dict.find(tmpstr);
			if(it != dict.end())
			{
				if(tmpstr.length() == s.length())return true;
				flag = wordBreak(s.substr(i),dict);
			}
			if(flag)return true;
		}
		return false;
    }


第二种方法:dpAccepted

思路:从s的第一个字母向后匹配,如果i前面的前缀可以匹配,就看s字符串i以后的后缀是否匹配,在找后缀是否匹配时添加了记忆功能。

bool wordBreakHelper(string s, unordered_set<string> &dict,set<string> &unmatch) {
        if(s.length() < 1) return true;
		bool flag = false;
		for(int i = 1; i <= s.length(); i++)
		{
			string prefixstr = s.substr(0,i);
			unordered_set<string>::iterator it = dict.find(prefixstr);
			if(it != dict.end())
			{
				string suffixstr = s.substr(i);
				set<string>::iterator its = unmatch.find(suffixstr);
				if(its != unmatch.end())continue;
				else{
					flag = wordBreakHelper(suffixstr,dict,unmatch);
					if(flag) return true;
					else unmatch.insert(suffixstr);
				}
			}
		}
		return false;
    }
	bool wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once.
        int len = s.length();
		if(len < 1) return true;
		set<string> unmatch;
		return wordBreakHelper(s,dict,unmatch);
    }

dp改进:dict中的单词有的长有的短,当prefixstr串小于最短串时就不匹配了,当prefixstr串大于最长的串时也不用匹配了。多谢@阿桂爱清净

bool wordBreakHelper(string s,unordered_set<string> &dict,set<string> &unmatched,int mn,int mx) {
        if(s.size() < 1) return true;
		int i = mx < s.length() ? mx : s.length();
		for(; i >= mn ; i--)
		{
			string preffixstr = s.substr(0,i);
			if(dict.find(preffixstr) != dict.end()){
				string suffixstr = s.substr(i);
				if(unmatched.find(suffixstr) != unmatched.end())
					continue;
				else
					if(wordBreakHelper(suffixstr, dict, unmatched,mn,mx))
						return true;
					else
						unmatched.insert(suffixstr);
			}
		}
        return false;
    }
	bool wordBreak(string s, unordered_set<string> &dict) {
        // Note: The Solution object is instantiated only once.
		if(s.length() < 1) return true;
		if(dict.empty()) return false;
		unordered_set<string>::iterator it = dict.begin();
		int maxlen=(*it).length(), minlen=(*it).length();
		for(it++; it != dict.end(); it++)
			if((*it).length() > maxlen)
				maxlen = (*it).length();
			else if((*it).length() < minlen)
				minlen = (*it).length();
        set<string> unmatched;
		return wordBreakHelper(s,dict,unmatched,minlen,maxlen);
    }




RPA与旅游与酒店行业自动化实战案例 1. 背景介绍 1.1 旅游与酒店行业的挑战 旅游与酒店行业是一个高度竞争的市场,企业需要不断提高服务质量、降低成本、提高效率以保持竞争力。在这个过程中,企业面临着诸多挑战,如客户需求多样化、市场变化快速、人力资源成本高昂等。为了应对这些挑战,企业需要寻求新的技术手段来提高运营效率。 阅读详情

相关推荐

转录组分析中的Fastp和FastQC:如何快速检测数据质量并优化流程

本文深入探讨了转录组分析中数据质量控制的核心流程,重点介绍了Fastp和FastQC两款工具的组合应用。FastQC负责对原始测序数据进行全面质量评估,生成可视化报告;Fastp则能一站式完成接头切除、低质量序列过滤、长度筛选等关键质控步骤。文章提供了详细的参数解读、实战脚本和自动化流程构建指南,帮助研究人员快速检测数据质量并优化预处理流程,为下游的差异表达等分析奠定可靠基础。

weixin_28452161的博客 195

leetcode题解:第139题Word Break

https://leetcode-cn.com/problems/word-break/ 文章目录解法一、回溯代码解法二、动态规划代码复杂度分析 解法一、回溯 依照惯例,没有好的思路的时候,就先想想暴力解法怎么做。暴力解法无非是逐个单词地拆分字符串,每次选的单词可以重复。要实现暴力解法的话,肯定就是用回溯,因为回溯算法“撤销选择”的特点,保证了每次都能考虑到所有的单词。 简而言之,对于字符串s和单词word,word长度为n,当word与s[:n]相同时,就可以把word选来进行一次拆分,紧接着继续判断s[

chenf1999的博客 542

Windows环境下DataEase一站式安装指南(含WSL2+Docker配置)

本文详细介绍了在Windows环境下通过WSL2和Docker快速部署DataEase的完整教程。从WSL2配置、Docker环境搭建到DataEase离线安装,逐步指导用户完成一站式部署,特别适合需要快速搭建数据分析平台的开发者。教程包含常见问题解决方案和性能优化技巧,帮助用户高效使用这款国产开源数据可视化工具。

weixin_42526166的博客 403

LeetCode——word-break(单词切分)

知识点:动态规划 本文首发于github 题目描述 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s =“leetc...

ai-exception的博客 614

从CMOS到CML:手把手教你为PLL选对分频器电路(附性能对比与选型指南)

本文深入解析了PLL分频器电路的三大主流架构——静态CMOS、动态TSPC和CML,通过性能参数对比和实测数据,提供了从频率需求、功耗预算到噪声防护的完整选型指南。特别针对高频应用的CML分频器设计要点和混合架构优化方案,为射频与模拟IC设计工程师提供实用参考。

weixin_30887919的博客 465

NV 英伟达2022数字芯片笔试题

作者:数字IC打工人 链接:【开卷】第27期 NV 英伟达2022数字芯片笔试题_笔经面经_牛客网 来源:牛客网 1、Single Choice: Given thefollowing FIFO and rules, how deep does the FIFO need to be to preventunderflow or overflow? RULES: clk_A=25MHz; clk_B=100MHz; en_B is periodically asserted: period.

weixin_44072819的博客 6403

[亚麻高频题] Leetcode 139. Word Break

题目描述&链接 Leetcode 139:判断字典中的字符能否合并成目标字符串 -这道题只用判断可行性。进阶版Word Break II是需要返回所有可能情况。 Note:这题确实出的好,让你同时需要考虑算法和优化处理,这道题AC之路着实坎坷,屡屡尝试都TLE了,最后学会了优化解结果去Lintcode上写又TLE,最后终于弄明白最优解。。。 相似题目 Leetcode 140:Word Break II Leetcode 472: Concatenated Words 题目...

ok1382038的博客 542

金蝶ERP元数据解析:字段属性与表结构映射实战

本文深入解析金蝶ERP元数据的核心价值与应用实践,详细介绍了字段属性与表结构映射的关键技术。通过缓存获取与工具类直连两种方案对比,结合实际案例展示元数据在数据库校验、动态表单生成等场景的应用,帮助开发者高效解决二次开发中的常见问题。

weixin_33738555的博客 441

leetCode !! word break

方法一:字典树+动态规划首先,创建node类,每个对象应该包含:一个node array nexts(如果有通往’a’的路,那么对应的nexts[0]就不该为null);一个boolean 变量(如果到达的这个字母恰好是字典中某个候选串的结尾,那么 标记end=true);然后,根据 字典,建立字典树;接着,使用动态规划的方式,检查目标字符串str是否可以用字典中的候选串拼出来。具体地,dp[i]表示 str[i…] 是否可以用字典中的候选串拼出来。

萝卜丝儿皮尔 695

EtherCAT IGH 驱动一个步进电机

EtherCAT IGH 驱动一个步进电机。

u014077947的博客 7293

华为OD机试 - 矩形绘制 - 数组、坐标偏移(Python/JS/C/C++ 双机位C卷 100分)

本专栏收录于《华为OD机试真题(Python/JS/C/C++)》。刷的越多,抽中的概率越大,私信哪吒,备注华为OD,加入华为OD刷题交流群,每一题都有详细的答题思路、详细的代码注释、3个测试用例、为什么这道题采用XX算法、XX算法的适用场景,发现新题目,随时更新。实现一个简单的绘图模块,绘图模块仅支持矩形的绘制和擦除。 当新绘制的矩形与已有图形重叠时,对图形取并集; 当新擦除的矩形与已有图形重叠时,对图形取差集。 给定一系列绘制和擦除操作,计算最终图形的面积。第一行为操作数N,接下来的N行格式为:d x1

学Java,找哪吒 842

leetcode经典题目之word-break

题目: 链接:https://www.nowcoder.com/questionTerminal/5f3b7bf611764c8ba7868f3ed40d6b2c?answerType=1&f=discussion 来源:牛客网 给定一个字符串s和一组单词dict,判断s是否可以用空格分割成一个单词序列,使得单词序列中所有的单词都是dict中的单词(序列可以包含一个或多个单词)。 例如: 给定s=“leetcode”; dict=["leet", "code"]. 返回true,因为"leetco

qq_41634872的博客 526

使用 MATLAB/Simulink 构建一个基于FOC控制的PMSM矢量控制仿真模型

本教程详细介绍了基于Simulink的永磁同步电机(PMSM)磁场定向控制(FOC)仿真建模过程。主要内容包括:PMSM电机参数设置、Clarke/Park变换模块设计、电流环PID控制器构建、SVPWM调制实现等关键步骤。教程提供了完整的建模流程、参数配置建议和仿真调试方法,并给出了PID整定技巧和进阶优化方向。通过该模型,可深入理解PMSM矢量控制原理,掌握高性能电机控制系统的建模技术,为伺服系统、电动汽车驱动等应用领域提供仿真基础。教程还推荐了使用PIDTuner工具进行参数优化,并提出了加入负载扰动

amy_mhd的博客 647

leetcode题目:Word Break和Word Break II

题目一: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict

woailiyin的专栏 1109

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LeetCode:word-break

LeetCode:word-break题目描述代码实现 题目描述 Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s ...

weixin_38436336的博客 290

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

LeetCode:Word Break

Word Break Total Accepted:89221Total Submissions:347438Difficulty:Medium Given a stringsand a dictionary of wordsdict, determine ifscan be segmented into a space-separa

walker lee 2349

深度学习工具包 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] 135: Word Break

[Problem] Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", dict =

1.02^365的成长裂变 3698

LeetCode139:Word Break

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s = "leetcode", di...

diehuojiang5959的博客 144

LeetCode: Word Break

LeetCode: Word Break LeetCode: Word Break Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more ...

weixin_34162695的博客 112

Leetcode: word-break

题目一:word-break Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, given s ="leet

felinewong的博客 278

leetcode word break java,leetcode: word-break

题目描述:Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.For example, givens ="leetcode",dict =["leet", "co...

weixin_30572265的博客 150

LeetCode139:Word Break

Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.For example, given s = “leetcode”, dict = [“leet”, “co

2785

leetcode笔记:Word Break

如果使用递归,会超时。这时使用动态规划即可解决问题,即将源字符串s从开始到结尾,分解成各个子串进行操作,对于这类字符串组合问题,需要掌握类似状态转移方程。

liyuefeilong的专栏 1633
上一篇: Leetcode: First Missing Positive
下一篇: Leetcode: Simplify Path
「已注销」
博客等级 码龄18年 586粉丝 234原创
评论 8
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值