Java accepted answer that beat 92.97% answers


  • 0
    S

    The idea is to set a reference point as the first char, loop through the string, when a char has an occurrence that is before the position of the char we are looking at which shall also be after the reference point, reset the reference point. if not, increase count.

    public int lengthOfLongestSubstring(String s) {
            int length = s.length();
            int ref = 0;
            int count = 0;
            int result = 0;
            for (int i = 0; i < length; i++){
                if (s.indexOf(s.charAt(i), ref) >= ref + count){
                    count++;
                }else{
                    ref = s.indexOf(s.charAt(i), ref) + 1;
                    count = i - ref + 1;
                }
                if (count > result){
                    result = count;
                }   
            }
            return result;
        }
    

Log in to reply
 

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