请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。
假设字符串中只包含从’a’到’z’的字符。
样例
输入:"abcabc" 输出:3
思路
滑动窗口思想:
使用左右指针确定窗口的大小。使用哈希表存储窗口内的字符,具体滑动过程如下:
1. 右指针先向右移动,如果哈希表内没有发现当前的字符,则加入哈希表,计数+1,指针继续右移;
2. 如果右指针指向的字符已存在,那么保持右指针不动,左指针右移,并从哈希表中剔除,计数值-1,直到窗口内不存在重复字符,再重复1;
3. 因为有可能遍历完了都没发现重复字符,这样就导致结果没有得到更新,因此循环结束时需要再判断一次。
class Solution {
public int longestSubstringWithoutDuplication(String s) {
if (s == null || s.length() == 0) {
return 0;
}
HashSet<Character> set = new HashSet<>();
int res = 1;
int tmp = 0;
int l = 0;
int r = 0;
while (r < s.length()) {
if (!set.contains(s.charAt(r))) {
tmp++;
set.add(s.charAt(r++));
} else {
res = Math.max(res,tmp);
tmp--;
set.remove(s.charAt(l++));
}
}
res = Math.max(res,tmp);
return res;
}
} 
京公网安备 11010502036488号