3. 无重复字符的最长子串
给定一个字符串 s ,请你找出其中不含有重复字符的 最长子串 的长度
示例 1:
输入: s = “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
示例 2:
输入: s = “bbbbb”
输出: 1
解释: 因为无重复字符的最长子串是 “b”,所以其长度为 1。
示例 3:
输入: s = “pwwkew”
输出: 3
解释: 因为无重复字符的最长子串是 “wke”,所以其长度为 3。
请注意,你的答案必须是 子串 的长度,“pwke” 是一个子序列,不是子串。
示例 4:
输入: s = “”
输出: 0
解法(滑动窗口)
class Solution {
public int lengthOfLongestSubstring(String s) {
int n = s.length(),ans = 0;
//如果字符串长度为0,返回0
if(n == 0) return 0;
//定义一个 map 数据结构存储 (k, v),其中 key 值为字符,value 值为字符位置 +1,加 1 表示从字符位置后一个才开始不重复
Map<Character,Integer> map = new HashMap<>();
//我们定义不重复子串的开始位置为 start,结束位置为 end
for(int start = 0,end = 0;end < n;end++){
char ch = s.charAt(end);
//随着 end 不断遍历向后,会遇到与 [start, end] 区间内字符相同的情况,此时将字符作为 key 值,获取其 value 值,并更新 start,此时 [start, end] 区间内不存在重复字符.无论是否更新 start,都会更新其 map 数据结构和结果 ans。
if(map.containsKey(ch)){
start = Math.max(start , map.get(ch));
}
map.put(ch , end+1);
ans = Math.max(end-start+1 , ans);
}
return ans;
}
}