当前位置:网站首页>【Hot100】3. 无重复字符的最长子串
【Hot100】3. 无重复字符的最长子串
2022-06-28 15:51:00 【王六六的IT日常】
中等题
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
题解:
滑动窗口
定义一个 map 数据结构存储 (k, v),其中 key 值为字符,value 值为字符位置 +1,加 1 表示从字符位置后一个才开始不重复。
定义不重复子串的开始位置为 start,结束位置为 end
随着 end 不断遍历向后,会遇到与 [start, end] 区间内字符相同的情况,此时将字符作为 key 值,获取其 value 值,并更新 start,此时 [start, end] 区间内不存在重复字符
无论是否更新 start,都会更新其 map 数据结构和结果 ans。
map的value直接存字符的下标更好理解,在map.get(c)的地方再进行+1操作。
代码:
class Solution {
public int lengthOfLongestSubstring(String s) {
int res = 0;
Map<Character,Integer> map = new HashMap<>();
for(int start = 0,end = 0;end < s.length(); end++){
char c = s.charAt(end);
if(map.containsKey(c)){
//相等字符第二次还没存进去,所以map中取到的就是之前存的一样字符的下标,start更新为下标的下一位置
start = Math.max(map.get(c) + 1 ,start);
}
res = Math.max(end - start + 1, res);
map.put(c,end);
}
return res;
}
}
边栏推荐
- Vc2010 compilation qt5.6.3 prompt cvtres: fatal error cvt1107:
- 首次失败后,爱美客第二次冲刺港交所上市,财务负责人变动频繁
- 机器学习之深度学习卷积神经网络,实现基于CNN网络的手写字体识别
- 10:00面试,10:02就出来了 ,问的实在是太...
- Change exchange (dynamic planning)
- 数组中的第K大元素[堆排 + 建堆的实际时间复杂度]
- among us私服搭建
- Visual Studio 2010 configuring and using qt5.6.3
- 早晨有些犹豫
- Basic grammar of C language
猜你喜欢

榜单首发——线控制动「新周期」,本土供应商市场竞争力TOP10

CODING DevOps 助力中化信息打造新一代研效平台,驱动“线上中化”新未来

Expand Disk C (allocate the memory of disk d to Disk C)
PostgreSQL enables grouping statistics by year, month, day, week, hour, minute and second

5 minutes to make a bouncing ball game

Visual Studio 2019软件安装包和安装教程

Installation and use of Jenkins

防火墙基础之流量管理与控制

【推荐系统】多任务学习之ESMM模型(更新ing)

Visual Studio 2010 配置和使用Qt5.6.3
随机推荐
Technical secrets of ByteDance data platform: implementation and optimization of complex query based on Clickhouse
麻烦问一下,我数据库中写入占99%查询很少,用按量付费模式还是预留模式比较好?
榜单首发——线控制动「新周期」,本土供应商市场竞争力TOP10
Go zero micro Service Practice Series (VII. How to optimize such a high demand)
Open source technology exchange - Introduction to Chengying, a one-stop fully automated operation and maintenance manager
Flutter dart语言特点总结
QT create 5.0.3 configuring qt4.8.7
Visual Studio 2019软件安装包和安装教程
Classic model transformer
一台服务器最大并发 tcp 连接数多少?65535?
Visual Studio 2010 compilation qt5.6.3
ID卡复制教程(使用T5577卡复制4100卡)
Big God explains open source buff gain strategy live lecture
知道这几个命令让你掌握Shell自带工具
C语言基础语法
IPDK — Overview
机器学习之卷积神经网络Lenet5训练模型
10年测试经验,在35岁的生理年龄面前,一文不值
简单介绍一下tensorflow与pytorch的相互转换(主要是tensorflow转pytorch)
Openharmony - detailed source code of Kernel Object Events