LeetCode-3:Longest Substring Without Repeating Characters

[LeetCode]--3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters.Examples:Given “abcabcbb”, the answer is “abc”, which the length is 3.Given “bbbbb”, the answer is “b”, with the le 阅读详情

一、题目

原题链接:https://leetcode.com/problems/longest-substring-without-repeating-characters/
难度等级:中等

Given a string, find the length of the longest substring without repeating characters.

Examples:
Given “abcabcbb”, the answer is “abc”, which the length is 3.
Given “bbbbb”, the answer is “b”, with the length of 1.

Given “pwwkew”, the answer is “wke”, with the length of 3. Note that the answer must be a substring, “pwke” is a subsequence and not a substring.

题目翻译:
给定一个字符串,找出其中无重复字符的最长子串的长度。
例如:
“abcabcbb”,无重复字符的最长子串是”abc”,长度为3。
“bbbbb”,无重复字符的最长子串是”b”,长度为1


二、解题方案

思路1:
通过Bitmap来统计是否子字符串中有重复的字符。遍历时若遇到重复值,需要回溯。

代码实现:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        map<char, int> m;
        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m.find(s[i]) != m.end() && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

        return maxLen;
    }
};

思路2:
通过一个数字来存储每一个字符上一次出现的位置,当出现冲突时及时调整。

代码实现:

class Sulution {
public:
    int lengthOfLongestSubstring(string s) {
        const int MAX_CHARS = 256;
        int m[MAX_CHARS];
        memset(m, -1, sizeof(m));

        int maxLen = 0;
        int lastRepeatPos = -1;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] != -1 && lastRepeatPos < m[s[i]]) {
                lastRepeatPos = m[s[i]];
            }
            if (i - lastRepeatPos > maxLen) {
                maxLen = i -lastRepeatPos;
            }
            m[s[i]] = i;
        }

        return maxLen;
    }
};
LeetCode 题解 3. Longest Substring Without Repeating Characters(最长不含重复字符的子字符串) 阅读详情

相关推荐

CATIA CAA开发环境搭建避坑指南:从授权服务到VS配置全流程

本文提供了一份详尽的CATIA CAA开发环境搭建避坑指南,涵盖从授权服务(DSLS)安装、Visual Studio版本匹配与集成配置,到编译调试全流程。重点解析了授权服务无法连接、模块加载失败等典型问题的解决方案,强调版本严格对应与纯英文环境是成功搭建的关键。

redis7keeper的博客 572

Longest Continuous Increasing Subsequence

    这道题为简单题   题目:        思路:     设置三个变量,max_long 存储总的最大长度,l代表该值目前的最大长度,num主要用来比较列表的前后大小。如果i大于num那么l就一直加1.否则l就和max_long比较大小,l变为1,num更新为i值   代码: 1 class Solution: 2 def findLengthOfLCI...

weixin_30799995的博客 150

物体检测之非极大值抑制:NMS、softNMS、softerNMS、IoU-Net

当前的物体检测算法为了保证召回率,对于同一个真实物体往往会有多个的候选框输出。由于多余的候选框会影响检测精度,因此需要利用NMS过滤掉重叠的候选框,得到最佳的预测输出。当前有如下几种较为常见的NMS方法, 1.基本NMS 非极大值抑制, 顾名思义就是抑制不是极大值的边框,这里的抑制通常是直接去掉冗余的边框。 这个过程涉及以下两个量化指标: 1.预测得分:NMS假设一个边框的预测得分越高,这个框...

LeoLee 1941

Longest Common Substring && Longest continuous Common History

longest continuous common history 输入: [ ["3234.html", "xys.html", "7hsaa.html"], // user1 ["3234.html", ''sdhsfjdsh.html", "xys.html", "7hsaa.h...

leetcode 解题思路 737

基于STM32F103的二维码识别项目——OV7670篇

此系列用于记录做过的项目,这篇文章介绍基于STM32F103的二维码识别项目之OV7670FIFO模块。

beyourself_he的博客 4287

一分钟教会你搭建steam新游幻兽帕鲁服务器

总结: 游戏对服务器搭建要求相对较高、且对服务器网络协议有要求不能封堵UDP、多开、游戏运行久、同时在线人数多了这些会很吃内存 我自己用的64G内存多开4区测试玩家同时在线50多人的情况下内存已经跑满了、对于想用服务器搭建联机的小伙伴建议根据开区数量以及玩家人数去选择配置、当然也可以直接找我阿杰购买、我可以提供技术搭建服务。注:如果用的是本地电脑局域网搭建直接输入127.0.0.1:8211就行 如果用的是服务器搭建输入自己服务器IP+端口或解析的域名+端口进入游戏。

用最简单的方式说最重要的事!服务器、存储、云计 算、A智能的大数据产品、游戏开发技术。致力于广 大开发者、政企用户、各项机构等,构建云上世界提供全方位云计算解决方案。旨在打造差异化的开放式闭环生态系统帮助用户快速构建稳定、安全的云计算环境。 2233

Longest Valid Parentheses 最长有效括号

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。 示例 1: 输入: "(()" 输出: 2 解释: 最长有效括号子串为 "()" 示例 2: 输入: ")()())" 输出: 4 解释: 最长有效括号子串为 "()()" 思路: 方法一:使用栈(stack)来做,基本思想是匹配"("和")",互相相消 { 如果栈顶是“(”且下一个元素是&

qq_26410101的博客 281

手把手教会你用yolov8从环境配置到检测任务实战

做本文章前,我浏览过很多网上资料,我发现他们总是写的含糊不清,而且实际操作起来就会有各种各样的问题,要么就是根本不适合一些小白,所以我在这里写一篇完全针对小白的yolo从入门到实战。看完本文章后大家都可以实现下图效果,数字识别是一种比较简单的检测任务,其他识别任务学完本例也能够一通百通,大家边做边学,更好的体会yolo的神奇之处。

KevenDuan的博客 2871

【leetcode】字符串的常见算法问题总结(LIS、LCS、LCP、LPS、ED、KMP)

字符串有很多比较经典的算法问题,例如:LIS(最长递增子序列)、LCS(最长公共子序列、最长公共子串)、LCP(最长公共前缀)、LPS(最长回文子序列、最长回文子串)、ED(最小编辑距离,也叫 “Levenshtein 距离”)、 KMP(一种字符串匹配的高效算法)。 上面列举的经典问题,在 Leetcode 中都有对应题型,这些也是笔试面试经常会遇到的基本题型。上面列举的三个经典匹配算法中,KM...

Deeven123的博客 8493

汽车电子零部件(14):TMS热管理系统

TMS(thermal management system)热管理系统,这是新能源汽车诞生后随之而产生的一种新汽车零部件,一旦热管理失控会触发自燃,这种现象也是对EV来说是件头疼的事。汽车的热管理系统(TMS)是一个关键部件,有助于调节汽车电池组、车厢和其他车辆系统的温度。TMS的主要目的是在驾驶过程中保持最佳的电池性能和乘客舒适度。TMS使用各种加热和冷却系统来调节电池组和车厢的温度,并通过优化其使用,降低能耗,提高车辆的整体效率。

码农17年的博客 3160

【Godot】【工程】中文字体与多语言(缺字/体积/打包:一次性配置到位)

本文介绍了Godot游戏开发中的中文字体配置与多语言支持方案。主要内容包括:1)中文字体的全局与局部设置;2)使用子集化技术减小字体体积;3)多语言资源管理及翻译系统实现;4)语言切换机制与控件刷新方法;5)字体回退策略优化显示效果;6)打包优化建议。文章提供了从字体导入到多语言实现的完整解决方案,帮助开发者系统性解决中文显示和多语言支持问题,同时优化资源体积和性能表现。配套案例可供学习参考。

技术小甜甜:传播可落地技术,帮助个人和企业降低解决真实场景问题的成本 596

第14题 find longest common continuous substring

Write Program to find longest common contiguous intersection from 2 lists provided to the function. Example: list1: abcrfghwetf list2: abrfghwwetxyab Longest common intersection here is: fghwN...

爱.NET 191

蓝牙模块HM-10手册

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

Leetcode 3 Longest Substring Without Repeating Characters

Leetcode 3 Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: Th...

博学 笃志 切问 近思 159

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

leetcode--3. Longest Substring Without Repeating Characters

尺取法 首先设置头尾两个指针,都指向头,然后尾指针开始遍历,在遍历过程中记录每个字母出现个数,每次遍历若当前字母没有出现过,则更新答案长度。若出现过,则将头指针移到重复字母的后面一位。然后继续重复上述操作。最后返回答案即可。 class Solution { public: int lengthOfLongestSubstring(string s) { if(s.le

林伏案的博客 457

深度学习工具包 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&#39;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(&#39;DeepLearnToolbox&#39;));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(&#39;state&#39;,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&#39;); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand(&#39;state&#39;,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 = &#39;sigm&#39;;%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, &#39;Too big error&#39;);```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(&#39;state&#39;,0)sae = saesetup([784 100]);sae.ae{1}.activation_function = &#39;sigm&#39;;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)&#39;)% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;;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, &#39;Too big error&#39;);```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x&#39;,28,28,60000))/255;test_x = double(reshape(test_x&#39;,28,28,10000))/255;train_y = double(train_y&#39;);test_y = double(test_y&#39;);%% 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&#39;ll get around 1.2% errorrand(&#39;state&#39;,0)cnn.layers = { struct(&#39;type&#39;, &#39;i&#39;) %input layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 6, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 2) %sub sampling layer struct(&#39;type&#39;, &#39;c&#39;, &#39;outputmaps&#39;, 12, &#39;kernelsize&#39;, 5) %convolution layer struct(&#39;type&#39;, &#39;s&#39;, &#39;scale&#39;, 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, &#39;Too big error&#39;);```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(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex2 neural net with L2 weight decayrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex3 neural net with dropoutrand(&#39;state&#39;,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, &#39;Too big error&#39;);%% ex4 neural net with sigmoid activation functionrand(&#39;state&#39;,0)nn = nnsetup([784 100 10]);nn.activation_function = &#39;sigm&#39;; % 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, &#39;Too big error&#39;);%% ex5 plotting functionalityrand(&#39;state&#39;,0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);%% 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(&#39;state&#39;,0)nn = nnsetup([784 20 10]); nn.output = &#39;softmax&#39;; % 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, &#39;Too big error&#39;);```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[LeetCode] 3. Longest Substring Without Repeating Characters 最长不重复子串

[LeetCode] 3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Expla...

weixin_30795127的博客 110

闯关leetcode——3.Longest Substring Without Repeating Characters

leetcode第三题

方亮的专栏 1340

[LeetCode]3. 无重复字符的最长子串(Longest Substring Without Repeating Characters)题解

在leetcode中该题网址:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 题目描述: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 ...

sultry_yi的博客 524

【Leetcode】3. Longest Substring Without Repeating Characters

题目地址: https://leetcode.com/problems/longest-substring-without-repeating-characters/ 题目大意是,给定一个字符串,求其中的一个子串不含重复字母,返回其长度。可以用双指针来做,用一个map保存快指针遍历到jjj的时候s[0,...,j]s[0,...,j]s[0,...,j]所有字母最后出现的位置,快指针从000向后遍......

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

LeetCode(3) Longest Substring Without Repeating Characters

LeetCode的第3题,给定一个字符串,找到其中的一个最长的字串,使得这个子串不包含重复的字符。 // // Solution.h // LeetCodeOJ_003_LongestUniqueSubstr // // Created by feliciafay on 11/21/13. // Copyright (c) 2013 feliciafay. All rights rese

BUILD 1万+

【LeetCode】3. Longest Substring Without Repeating Characters

题目: Given a string, find the length of thelongest substringwithout repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Exampl...

希望的专栏 445

LeetCode之3. Longest Substring Without Repeating Characters

LeetCode上给的解决办法尝试 #1 暴力方法思考 一个个查看所有的子字符串看看是否没有相同的字符 算法 ——假设我们有一个函数,boolean allUnique(String substring),这个函数在String的每个子字符串中的字符都是两两不同的时候返回True。我们可以迭代字符串S中的所有子字符串并调用allUnique这个函数。如果返回True的话,我们就更新不

梦想,就现在! 485

[LeetCode] 3. Longest Substring Without Repeating Characters

题目链接: https://leetcode.com/problems/longest-substring-without-repeating-characters/description/ DescriptionGiven a string, find the length of the longest substring without repeating characters.Examples

从入门到扑街 424

Leetcode 3. Longest Substring Without Repeating Characters

3. Longest Substring Without Repeating Characters Given a string, find the length of the longest substring without repeating characters. Examples: Given "abcabcbb", the answer is "abc", which

ysCover 374

LeetCode 3:Longest Substring Without Repeating Characters

滑动窗口方法滑动窗口例题 滑动窗口 滑动窗口是数组/字符串问题中常用的抽象概念。 窗口通常是在数组/字符串中由开始和结束索引定义的一系列元素的集合。 例题 LeetCode 3:无重复字符的最长子串 使用 HashSet 作为滑动窗口, 将字符存储在当前窗口 [i, j)最初 j = i)中。 然后我们向右侧滑动索引 j,如果它不在 HashSet 中,也就是当前窗口没有重复字符时,继续滑动 ,也...

qq_24367757的博客 235
上一篇: LeetCode-2:Add Two Numbers
下一篇: LeetCode-4:Median of Two Sorted Arrays
7-sevens
博客等级 码龄10年 259粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值