Given a string, find the longest substring without any repeating characters and return the length of it. The input string is guaranteed to be not null.
For example, the longest substring without repeating letters for "bcdfbd" is "bcdf", we should return 4 in this case.
Solution: 用hashset记录出现过的字母,重复时,一直删之前的字母,直到hashset不含有该字母,再把字母加入hashset, count++
public int longest(String input) {
// Write your solution here.
if (input.length() < 2) {
return input.length();
}
Set<Character> hashset = new HashSet<>();
int max = 0, count = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (hashset.contains(c)) {
max = Math.max(max, count);
while (hashset.contains(c)) {
hashset.remove(input.charAt(i - count));
count--;
}
}
hashset.add(c);
count++;
}
max = Math.max(max, count);
return max;
}