Attempt at “Longest Substring Without Repeating Characters” in Java [duplicate]

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<>();
        for (int j = i+1; j< s.length(); j++){
            Character b = s.charAt(j);
            if (chars.contains(b))
        if (chars.size() > max)
            max = chars.size();
    return max;

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top