As Jimmy points out, you do indeed miss even long runs of the same character as long as the run isn’t of the character that starts the sequence you are testing. Here’s a solution that I believe works in all cases:
public static int lengthOfLongestSubstring(String s) {
if (s.length() == 0) return 0;
if (s.length() == 1) return 1;
int max = 0;
for (int i = 0;i<s.length();i++){
Set<Character> chars = new HashSet<>();
chars.add(s.charAt(i));
for (int j = i+1; j< s.length(); j++){
Character b = s.charAt(j);
if (chars.contains(b))
break;
chars.add(b);
}
if (chars.size() > max)
max = chars.size();
}
return max;
}
CLICK HERE to find out more related problems solutions.