3. 无重复字符的最长子串


  1. 无重复字符的最长子串

难度中等3949

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

​输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。 ​


1.滑动窗口问题

a.left记录当前窗口的左边界 i为右边界。

b.每次存储当前ch value为当前的坐标值

c.动态更新left 和 max的值

时间复杂度为O(n) 空间复杂度为O(n)

//滑动窗口问题。
//定义一个left 和 max 将s存储到map中 key为char value为i
//每次去map中查找是否有ch 有的话 修改left的值
//然后每一轮 记录max的最大值
//时间复杂度为O(n) 空间复杂度为O(n)
public int lengthOfLongestSubstring(String s) {
if(s == null){
return 0;
}
int max = 0;
int left = 0;
HashMap<Character,Integer> hashMap = new HashMap<Character,Integer>();
for(int i=0;i<s.length();i++){
char ch = s.charAt(i);
if(hashMap.containsKey(ch)){
left = Math.max(left,hashMap.get(ch)+1);//加1是因为aab 第二个a和之前的a相遇
//直接跳转到b位置 下一个位置从先滑动
}
hashMap.put(ch,i);
max = Math.max(max,i-left+1);//+1是因为 i-left是下标值0开始的
}
return max;
}