Given a string, find the length of the longest substring without repeating characters. 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.
code
public class LongestSubstring {
public int lengthOfLongestSubstring(String s) {
if (s == null || s.length() == 0)
return 0;
Set<Character> hashSet = new HashSet<Character>();
int maxLength = 0;
int leftBound = 0;
for (int i = 0; i < s.length(); i++) {
if (hashSet.contains(s.charAt(i))) {
while (leftBound < i && s.charAt(leftBound) != s.charAt(i)) {
hashSet.remove(s.charAt(i));
leftBound++;
}
leftBound++;// point to next index
} else {
hashSet.add(s.charAt(i));
maxLength = Math.max(maxLength, i - leftBound + 1);
}
}
return maxLength;
}
}