Longest Substring Without Repeating Characters
java
description:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
class Solution {
public int lengthOfLongestSubstring(String s) {
Set<Character> newHashSet = new HashSet<>();
int length = 0;
int maxLength = 0;
int index = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!newHashSet.contains(c)) {
newHashSet.add(c);
length++;
} else {
while (s.charAt(index) != c) {
newHashSet.remove(s.charAt(index));
index++;
}
index++;
length = i + 1 - index;
}
maxLength = Math.max(length,maxLength);
}
return maxLength;
}
}
java解题思路
- 首先初始化一个Hashset(newHashSet),定义三个int变量length,maxLength,index,初始值都为0
- for循环Sting变量s
- 每次循环将s的当前字符赋值给char变量c
- if用来判断当前字符在newHashSet是否存在
- 如果不存在则添加字符到newHashSet中,长度加1
- 如果存在则进行while循环,删除重复的字符第一次出现的位置
- index长度加1,用来下次字符相同时,直接从index位置开始判断
- 计算当前长度
- 使用max函数将最大值赋值给maxLength
- 返回maxLength