题目描述:
标签:哈希表 双指针 字符串 Sliding Window
给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。
代码:
思路分析:哈希表 滑窗思想(双指针)
①定义一个hashset存储已经统计过的字符。定义双指针,begin指向子串的头,end指向子串的尾,在遍历字符串中不断更新begin和end。定义一个count变量存储子串的最大长度。
②首先判断str[end]是否存在hashset中,使用了set.contains(Object key)的方法。
=>如果不存在,就添加str[end]到set中,并将end后移。同时比较此时的子串长度与最大长度之间的关系取较大值。
=>如果存在,就将str[begin]从set中移除,并将begin后移。再次比较str[end]是否包含,循环直到将重复的那个元素移出set,此时begin应该指向重复元素的下一个位置。
class Solution {
public int lengthOfLongestSubstring(String s) {
int len = s.length();//记录字符串的长度
char[] str = s.toCharArray();//把字符串转换为字符数组
Set<Character> set = new HashSet<Character>();
int begin = 0;//定义子字符串的头指针
int end = 0;//定义子字符串的尾指针
int count = 0;//记录子字符串的长度
while(end < len && begin < len){
if(set.contains(str[end])){
set.remove(str[begin]);
begin++;
}else{
set.add(str[end]);
count = Math.max(count , end - begin + 1);
end++;
}
}
return count;
}
}
滑窗思想:参考https://www.cnblogs.com/liang24/p/13595458.html。(虽然我这里好像直接把它当成双指针用了)