本文已参与[新人创作]活动,一起开启掘金创作之路。
[题目链接源](3. 无重复字符的最长子串 - 力扣(LeetCode) (leetcode-cn.com))
题目
给定一个字符串s,
请你找出其中**不含有重复字符最长子串**的长度。
思路
遍历字符串,用双指针遍历,map存储 分别设置指针left和right,初始化为0; (注意:left为无重复字符的最长子串的第一个字符) 设置变量maxLength记录最大子串的长度,初始化为0 遍历结束条件为right<s.length(); 分为两种情况 如果map中不存在该字符,则将字符存入map中,更新不重复子串的最大长度
//不存在
if(!map.containsKey(ch)){
//存入map中
map.put(ch,right);
//更新最大长度
maxLength=Math.max(maxLength,right-left+1);
right++;
}
如果map中存在该字符,更新lelft,更新不重复子串的最大长度
//存在该遍历的字符
else{
//更新不重复子串的第一个字符的位置
left=Math.max(left,map.get(ch)+1);
//更新最大长度
maxLength=Math.max(maxLength,right-left+1);
//更改重复子串的位置
map.put(ch,right);
right++;
}
示例
代码
class Solution {
public int lengthOfLongestSubstring(String s) {
// 哈希存储
Map<Character,Integer>map=new HashMap<>();
// 双指针
// 注意:left表示的是无重复字符的子串的第一个字符的位置
int left=0,right=0;
// 记录无重复字符的最长子串的长度
int maxLength=0;
// 遍历字符串
while(right<s.length()){
// 记录遍历的字符
char ch=s.charAt(right);
// 判断map中是否存在该字符
// 不存在该字符
if(!map.containsKey(ch)){
// 存入字符
map.put(ch,right);
// 更新最大长度
maxLength=Math.max(maxLength,right-left+1);
right++;
}
// 存在该字符
else{
// 更新无重复字符的第一个字符的位置
left=Math.max(left,map.get(ch)+1);
// 更新最大长度
maxLength=Math.max(maxLength,right-left+1);
// 更新重复字符的位置
map.put(ch,right);
right++;
}
}
return maxLength;
}
}
小结
学习滑动窗口
Map