Why is my codes wrong?


  • 0
    K

    public class Solution {
    public int lengthOfLongestSubstring(String s) {
    if(s.length() == 0)
    return 0;

        int maxlen = 1;
        char[] c = s.toCharArray();
        LinkedList queue = new LinkedList();
        queue.add(c[0]);
        
        for(int i = 1; i < c.length; i ++){
            if(queue.contains(c[i])){
                maxlen = queue.size() > maxlen ? queue.size() : maxlen;
                queue.clear();
                queue.add(c[i]);
            }else{
                queue.add(c[i]);
            }
        }
        
        return queue.size() > maxlen ? queue.size() : maxlen; // compare for last string;
    }
    

    }


  • 0
    F

    example:
    "abcbdef"
    in your case, when you reach the second b, you clear the queue and add b.
    so your longest string is bdef
    In fact, the longest string is cbdef.
    the starting point for the next substring is not the second b, but the char after the first b.


  • 0
    S

    for example , s= "abcdbde" , the max = 4 , substr = "abcd"
    with your code, when detect the second char 'b', you just clear all the elements of the queue, next your start begins from second b just ignoring previous substr .


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.