Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
Example
For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
For "bbbbb" the longest substring is "b", with the length of 1.
Notes:
- Forward two pointers
- Apply template
- Use HashSet to judge whether substring contains repeated characters
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0) {
return 0;
}
Set<Character> set = new HashSet<>();
int n = s.length();
int j = 0;
int max = 0;
for (int i = 0; i < n; ++i) {
while(j < n && !set.contains(s.charAt(j))) {
set.add(s.charAt(j));
j++;
}
max = Math.max(max, s.substring(i, j).length());
set.remove(s.charAt(i));
}
return max;
}