当前位置:网站首页>无重复字符的最长字串
无重复字符的最长字串
2022-07-29 05:09:00 【小洪正在努力】

这是力扣的一道题目,最开始尝试着用动态规划解决,可以是可以,但是看了题解之后觉得滑动窗口也是一个很妙的解题方法,学习了一下做了个小总结。
1.遍历字符串,并再定义一个指针,初始化该指针指在字符串的最左边
2.判断当前指针指向的字符是否在集合中出现过。
1)如果未出现,将该字符添加到集合中,并且让指针不停往下一个字符移动;
2)如果出现了,停止移动。
3.获取当前截止的字符串长度,并与上一个字符串进行比较。
流程示意:
从流程中可以很直观的看出最长的字串长度。
滑动窗口就好比队列,第一个进来的再找到重复的字符后就第一个离开,然后再循环判断。
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> set = new HashSet<>();
int index = 0;//定义右指针
int max = 0;
for(int i = 0;i < s.length();i++){
if(i!=0){
set.remove(s.charAt(i-1));
}
while(index < s.length()&&!set.contains(s.charAt(index))) {
set.add(s.charAt(index));
index++;
}
max = Math.max(max,index - i);
}
return max;
}
}
边栏推荐
- 抽象类与接口
- C语言数组入门到精通(数组精讲)
- 一维数组练习
- Introduction to array learning simple question sum of two numbers
- Xiaobai high salary shortcut Qt development game Snake
- Cryengine3 debugging shader method
- 如视技术副总裁杨永林:当传统产业遇到“数字空间”
- JD cloud golden autumn cloud special offer is in progress! Code scanning participation activities
- Live broadcast preview | how to improve enterprise immunity through "intelligent edge security"?
- More than 200 ISVs have settled in! The first anniversary of Alibaba cloud computing nest
猜你喜欢

Unity3d - the object is too far away to see

直播预告|如何节省30%人工成本,缩短80%商标办理周期?

Li Yan, CEO of parallel cloud: cloudxr, opens the channel to the metauniverse

【剑指offer】— 详解库函数atoi以及模拟实现atoi函数
![[event preview] cloud digital factory and digital transformation and innovation forum for small and medium-sized enterprises](/img/6f/f7c5d605ea9b7b9e7c49ac716492ef.jpg)
[event preview] cloud digital factory and digital transformation and innovation forum for small and medium-sized enterprises

Live broadcast preview | how to save 30% labor cost and shorten 80% trademark processing cycle?

携手数字人、数字空间、XR平台,阿里云与伙伴共同建设“新视界”

阿里云架构师梁旭:MES on 云盒,助力客户快速构建数字工厂

OCCT学习003-----MFC单文档工程

QML control: combobox
随机推荐
Cryengine5 shader debugging
osg进阶-序
osgSimplegl3结合RenderDoc工具
递归的基本原理
直播预告|如何节省30%人工成本,缩短80%商标办理周期?
研发效能|Kubernetes核心技术剖析和DevOps落地经验
C语言数组入门到精通(数组精讲)
QtCreator+CMake编译器设置
【赛事预告】云上开发,高效智能——第二届阿里云ECS CloudBuild开发者大赛即将启动
千人规模互联网公司研发效能成功之路
AD常用快捷键
365天挑战LeetCode1000题——Day 039 完全二叉树插入器 + 寻找峰值 II + 快照数组
直播预告|如何通过“智能边缘安全”提升企业免疫力?
osgSimplegl3例子分析
167. Sum of two numbers II - enter an ordered array
More than 200 ISVs have settled in! The first anniversary of Alibaba cloud computing nest
哈夫曼树以及哈夫曼编码在文件压缩上的应用
321, Jingdong Yanxi × Nlpcc 2022 challenge starts!
【C语言系列】— 不创造第三个变量,实现两个数的交换
Cryengine3 debugging shader method