---
Solution: Add each character as we see it. Keep the current length of the longest substring ending at current index. If we have a duplicate character, then reduce the length of the current longest substring until there are no more duplicate characters.
public class Solution {
public int lengthOfLongestSubstring(String s) {
if (s.isEmpty()) return 0;
int longest = 0;
int current = 0;
Set<Character> seen = new HashSet<>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (seen.contains(c)) {
while (current > 0) {
char d = s.charAt(i - current);
seen.remove(d);
current--;
if (c == d) break;
}
}
seen.add(c);
current++;
longest = Math.max(longest, current);
}
return longest;
}
}
No comments:
Post a Comment