Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

java - Longest Substring Without Repeating Characters: Wrong answer

I have sent hours trying to find out the reason why the method returns a wrong answer for this particular test case: "qrsvbspk". The method returns 6 instead of 5. I cannot figure out what is wrong. Plz help!

Here's my approach:

class Solution {
    public int lengthOfLongestSubstring(String s) {
        int i = 0;
        int max_count = -1;
        int count = 0;
        
          if(s.length() == 0)
              return 0;
        
        HashSet<Character> set = new HashSet();
        
        int k = 0;
        while(k < s.length()){
            i = k;
            while(i < s.length() && !set.contains(s.charAt(i))){
                count++;
                set.add(s.charAt(i++));
            }
            if(count >= max_count){
                max_count = count;
                set.clear();
                count = 0;
            } 
                k++;
        }
        return max_count;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In the answer, iota has already mentioned the root cause behind the problem. I am adding another way of finding the length of the longest substring.

  1. Using a nested loop, check all substrings, starting from a position till the end of the string, for the uniqueness of characters.
  2. Update the value of max (a variable to track the length of the longest substring) if a substring is found to be of greater length.

Demo:

public class Main {
    public static void main(String[] args) {
        // Test
        System.out.println(lengthOfLongestSubstring("qrsvbspk"));
    }

    public static int lengthOfLongestSubstring(String s) {
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            for (int j = s.length(); j >= i; j--) {
                int len = j - i;
                if (s.substring(i, j).chars().distinct().count() == len && len > max) {
                    max = len;
                }
            }
        }
        return max;
    }
}

Output:

5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...