算法-剑指offer 48. 最长不含重复字符的字符子串
题目:最长不含重复字符的字符子串
1. 示例1
输入: "abcabcbb"
输出: 3
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3。
2. 示例2
输入: "bbbbb"
输出: 1
解释: 因为无重复字符的最长子串是 "b",所以其长度为 1。
3. 解题方法:双指针
采用两个指针记录最大不重复子串的左右区间,使用HasHSet维护范围内所含有的字符集合。在快指针向后扫描时,如果集合中不存在此元素则直接将字符加入集合,否则慢指针后扫描至与快指针相同的字符之后,同时将所有扫描路径上的字符从集合中删除。具体代码如下:
class Solution {
public int lengthOfLongestSubstring(String s) {
if(s == null || s.length() == 0){
return 0;
}
int start = 0;
int end = 0;
HashSet<Character> set = new HashSet<>();
int max = Integer.MIN_VALUE;
while(end < s.length()){
char ch = s.charAt(end);
if(set.contains(ch)){
int len = end - start;
if(len > max){
max = len;
}
while(start <= end && s.charAt(start) != ch){
set.remove(s.charAt(start));
++start;
}
start++;
}else{
set.add(ch);
}
++end;
}
if(end - start > max){
max = end - start;
}
return max;
}
}
~~~Java