LeetCode 3 无重复字符的最长子串 题解
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度。
示例 1:
输入: s = "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
示例 2:
输入: s = "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
示例 3:
输入: s = "pwwkew"
输出: 3
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 3。
请注意,你的答案必须是 子串 的长度,"pwke" 是一个子序列,不是子串。
示例 4:
输入: s = ""
输出: 0
提示:
0 <= s.length <= 5 * 104
s 由英文字母、数字、符号和空格组成
方法:滑动窗口
HashMap(字符,索引值),碰到相同的char就把left移到最右边的【因为可能有很多个相同的字符】
这个字符的右边一位,right一直右移
时间复杂度:O(n):只需要遍历一次数组,hashmap查找key复杂度是O(1)
空间复杂度:O(m):其中m是字符集大小
import java.util.HashMap;
class Solution {
public int lengthOfLongestSubstring(String s) {
//1.滑动窗口1
// //这题题目给出了范围,不用判空
// int max = 0, left = 0;
// HashMap<Character, Integer> cToIndex = new HashMap<>();
// //right同时也是当前字符的索引值
// for(int right = 0; right < s.length(); right++){
// char c = s.charAt(right);
// if(cToIndex.containsKey(c)){
// left=Math.max(left,cToIndex.get(c)+1);//left一定要跳到当前窗口左边界的右边,不能往回跳,eg:abcdca或abba在第二次遇到a的时候
// }
// cToIndex.put(c, right);//这里遇到相同的字符话,因为是相同的key,所以会更新value值为相同字符中最右边的字符的index
// max = Math.max(max, right-left+1);
// }
// return max;
//2.滑动窗口2
//记录当前left-right区间已经出现的字符
Set<Character> chars = new HashSet<>();
int maxLen = 0,right = -1, n = s.length();
for(int left = 0; left < n; left++){
if(left > 0){
//左指针右移,从集合中删去当前最左边的元素
chars.remove(s.charAt(left-1));
}
while((right+1) < n && !chars.contains(s.charAt(right+1))){//右边界可以右移的条件
chars.add(s.charAt(right + 1));
right++;
}
maxLen = Math.max(maxLen, right - left + 1);
}
return maxLen;
}
}