当前位置:网站首页>每日一题-无重复字符的最长子串-0712
每日一题-无重复字符的最长子串-0712
2022-08-05 05:17:00 【菜鸡程序媛】
题目:给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
解题思路:在map中存放字符串字符,当存在已有字符和当前的字符相等时,要更新滑动窗口的start,要取max(start, s.charAt(i) +1),因为当存在的相等的字符在更前面时,就会造成错误的区域划分,如"tmmzuxt",不取最大值的话,就会把第一个m当成新的开始值,但是m自身已经是重复的字符了。
其实可以这样想,如果start没有变大的话,就证明一直没有重复的字符出现过;既然有更大的值,就证明前面已经有重复的了,只能取更大的。即滑动窗口的左边届开始的后面不应该有重复的字符。
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0)
return 0;
int left = 0;
int max = 0;
Map<Character, Integer> map = new HashMap<>();
for(int i = 0; i < s.length(); i ++){
if(map.containsKey(s.charAt(i)))
left = Math.max(left, map.get(s.charAt(i)) + 1);
// 在更新重复的字符,如上面的第一个m和第二个m,第二个m写入就会把第一个覆盖掉
map.put(s.charAt(i), i);
max = Math.max(max, i - left + 1);
}
return max;
}
}
边栏推荐
猜你喜欢
MySQL主从复制—有手就能学会的MySQL集群搭建教程
[Database and SQL study notes] 8. Views in SQL
HuiFer 带你读懂 BeanFactory getBean 方法
It turns out that the MAE proposed by He Yuming is still a kind of data enhancement
LeetCode刷题之第23题
六、请求处理—获取请求参数系列注解是怎样工作的?
[Kaggle project actual combat record] Steps and ideas sharing of a picture classification project - taking leaf classification as an example (using Pytorch)
【Shell编程】第一章:子串
【shell编程】第二章:条件测试语句
【论文阅读-表情捕捉】ExpNet: Landmark-Free, Deep, 3D Facial Expressions
随机推荐
Redis设计与实现(第一部分):数据结构与对象
网络通信及相关函数介绍
函数在开发环境中的应用(简易实例)
《基于机器视觉测量系统的工业在线检测研究》论文笔记
读论文 - Unpaired Portrait Drawing Generation via Asymmetric Cycle Mapping
[Database and SQL study notes] 10. (T-SQL language) functions, stored procedures, triggers
八、响应处理——ReturnValueHandler匹配返回值处理器并处理返回值原理解析
[Intensive reading of the paper] R-CNN's Bounding box regression problem is detailed
LeetCode刷题之第701题
「实用」运维新手一定不能错过的17 个技巧
C语言入门笔记 —— 初识
[Pytorch study notes] 9. How to evaluate the classification results of the classifier - using confusion matrix, F1-score, ROC curve, PR curve, etc. (taking Softmax binary classification as an example)
【22李宏毅机器学习】课程大纲概述
tensorflow的session和内存溢出
The University of Göttingen proposed CLIPSeg, a model that can perform three segmentation tasks at the same time
十一、拦截器运行原理
5G中切片网络的核心技术FlexE
SharedPreferences and SQlite database
OSPF网络类型
【UiPath2022+C#】UiPath数据类型