# 3. 无重复字符的最长子串

120

``````输入: "abcabcbb"

``````

``````输入: "bbbbb"

``````

``````输入: "pwwkew"

请注意，你的答案必须是 子串 的长度，"pwke" 是一个子序列，不是子串。
``````

``````class Solution {
public int lengthOfLongestSubstring(String s) {

}
}
``````

``````int num = 0;
//TODO
return num;
``````

``````"abcabcbb"

"bca"
"cab"
"abc"
"bc"
"cb"
"b"
"b"
``````

``````public static int lengthOfLongestSubstring(String s) {
int num = 0;
//用于存放字符串
HashSet<Character> hashSet;
//从最开始循环到最后
for (int i = 0; i < s.length(); i++) {
hashSet = new HashSet<>();
//每次从i个开始循环
for (int j = i; j < s.length(); j++) {
//如果存在则退出
if (hashSet.contains(s.charAt(j))) {
break;
}
//不存在添加
//判断集合的大小
if (num < hashSet.size()) {
num = hashSet.size();
}
}
}
return num;
}
``````

## 优化

``````"abcabcbb"

//遇到a踢出a以及a之前的
"bca"
//遇到b踢出b以及b之前的
"cab"

"abc"

"cb"

"b"
``````

``````public static int lengthOfLongestSubstring(String s) {
int num = 0;
//记录从第几个元素开始移除
int count = 0;
HashSet<Character> hashSet = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
//如果集合以包含
while (hashSet.contains(s.charAt(i))) {
hashSet.remove(s.charAt(count));
count++;
}
//添加新的元素