Why is this code not executing properly? Longest substring problem

100 Views Asked by At

So I'm trying to solve the Longest Substring Without Repeating Character problem in a webpage and when I'm trying to upload it it will show me this bug:

class Solution {
public int lengthOfLongestSubstring(String s) {
    HashSet<Character> hash = new HashSet<>();
    int count = 0, finalCount = 1;
    char prevChar = s.charAt(0);
    hash.add(prevChar);


    for (int i = 1; i < s.length(); i++)
    {
        char character = s.charAt(i);
        if (!hash.contains(character)){
            hash.add(character);
            count++;
            if (count > finalCount) finalCount = count;
        }
        else{
            hash.clear();
            hash.add(character);
            count = 1;
        }
        prevChar = character;
    }
    return finalCount;
} }

enter image description here

Is there anything wrong with it? If not, do you think my algorithm was efficient? I can't compare its performance since the webpage won't let me upload it.

2

There are 2 best solutions below

0
On

You call s.charAt(0) in line 5. I imagine they pass in the empty string as a test case and you are getting an out of bounds exception. Prior to line 5 add a check to see if the string length is 0 and if it is return 0.

0
On

According to the error description it's doing a dummy-spit at line 5 of the Solution class.

Based on the picture that's:

char prevChar = s.charAt(0);

The error is ArrayIndexOutOfBounds which generally indicates you tried to get more out of something than was actually there (e.g. running over the end of an array).

Here I'd suggest maybe putting in some System.out.println lines at line 3 to sanity check the method parameter, e.g.:

(a) if the input String s is null

or

(b) if the input String s is empty (e.g. "")

charAt(0) will get the first character, but if there are zero characters then trying to get the 1th character is an error, no?

NB: something like this:

 System.out.println("Input was :" + s + ":");

Will show both of those conditions, as either:

Input was ::

for an empty String

Input was :null:

for a null String