博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode——3. Longest Substring Without Repeating Characters
阅读量:3526 次
发布时间:2019-05-20

本文共 1458 字,大约阅读时间需要 4 分钟。

1. 概述

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.

这道题需要求取的是在一个字符串中,最长的非重复子串。想到的便是记录扫描过的元素添加到集合中,若是判断新加如的字符与之前的重复了,那么就删除字符,直到不重复为止,在这个过程中记录最大的长度。
这里使用到的方法是 滑动窗口算法(Slide Window Algorithm)求解,和 Minimum Size Subarray Sum 相似。
设下标 l 和 r, 把左开右闭 [l, r) 想象成一个窗口。
当 s[r] 和窗口内字符重复时, 则 l 向右滑动,缩小窗口。
当s[r] 和窗口内字符不重复时,则 r 向右滑动,扩大窗口,此时窗口内的字符串一个无重复子字符串。
在所有的无重复子字符串中,找到长度最大的,即为原问题解。

2. 编码

class Solution {public:    int lengthOfLongestSubstring(string s)    {        if("" == s) return 0;   //空串        if(1 == s.length()) return 1;   //只有一个字符        if(2==s.length() && s.at(0)!=s.at(1)) return 2;                int left(0), right(1), len(s.length()), max_len(1);        unordered_set
setv; setv.insert(s.at(left)); while(right < len) { if(setv.count(s.at(right)) != 0) { setv.erase(s.at(left)); ++left; } //在集合中删除元素,直到没有与当前字符重复的时候 else { setv.insert(s.at(right)); ++right; max_len = max(max_len, (int)setv.size()); //记录最大的长度 } } return max_len; }};

转载地址:http://eykhj.baihongyu.com/

你可能感兴趣的文章
pytorch(四)
查看>>
pytorch(5)
查看>>
pytorch(6)
查看>>
opencv 指定版本下载
查看>>
ubuntu相关
查看>>
C++ 调用json
查看>>
nano中设置脚本开机自启动
查看>>
动态库调动态库
查看>>
Kubernetes集群搭建之CNI-Flanneld部署篇
查看>>
k8s web终端连接工具
查看>>
手绘VS码绘(一):静态图绘制(码绘使用P5.js)
查看>>
手绘VS码绘(二):动态图绘制(码绘使用Processing)
查看>>
基于P5.js的“绘画系统”
查看>>
《达芬奇的人生密码》观后感
查看>>
论文翻译:《一个包容性设计的具体例子:聋人导向可访问性》
查看>>
基于“分形”编写的交互应用
查看>>
《融入动画技术的交互应用》主题博文推荐
查看>>
链睿和家乐福合作推出下一代零售业隐私保护技术
查看>>
Unifrax宣布新建SiFAB™生产线
查看>>
艾默生纪念谷轮™在空调和制冷领域的百年创新成就
查看>>