Home > front end >  Longest substring without repeating character(Leetcode)
Longest substring without repeating character(Leetcode)

Time:03-27

I found a lot of solutions for this but I am just trying to understand why my code doesn't work. Basically I've taken two arrays. In one I added all characters until I found repetition. If a character repeats I converted all elements in the array to string, found their length and send it to another arrays. Lastly I sorted the second array and printed the largest length.

    public int lengthOfLongestSubstring(String s) {
        char a[]=new char[s.length()];
        int b[]=new int[s.length()];
        StringBuilder sbf = new StringBuilder("");
        for(int x=0;x<s.length();x  ){
            char c=s.charAt(x);
            if (new String(a).indexOf(c) == -1) {
                sbf.append(a);
                b[x]=sbf.length();
                sbf=null;
            }
            else
            {
                a[x]=c;
            }
        }
        Arrays.sort(b);
        return b[(b.length)-1];
    }
}

This was my error message

WARNING: A command line option has enabled the Security Manager
WARNING: The Security Manager is deprecated and will be removed in a future release

java.lang.NullPointerException: 
Cannot invoke "java.lang.StringBuilder.append(char[])" 
because 
"<local4>" is null 
at line 10, Solution.lengthOfLongestSubstring 
at line 54, __DriverSolution__.__helper__ 
at line 84, __Driver__.main

The link for the problem

CodePudding user response:

I don't comment your logic but just point out the mistake.

Let's say this lines execute

if (new String(a).indexOf(c) == -1) {
            sbf.append(a);
            b[x]=sbf.length();
            sbf=null;
        }

After that, StringBuilder sbf is null and next time when it tries to append it fails because it is already null.

CodePudding user response:

You're setting sbf to null and then trying to call a method on it on the next iteration. You should set its length to 0 to reset it instead:

sbf.setLength(0);

You also want to change the condition of your loop to:

if (new String(a).indexOf(c) != -1)
  • Related