Easy to understand solution


  • 0
    N
    public int lengthOfLongestSubstring(String s) {
        if(emptyString(s)){
            return 0;
        }
        char[] array = s.toCharArray();
        int lastIndex = 0;
        int max = 1;
        for(int i=1;i<array.length;i++){
            lastIndex = leftMostDistinctIndex(lastIndex,i,array);
            max = Integer.max(max,i-lastIndex+1);
        }
        return max;
    }
    
    private int leftMostDistinctIndex(int lastIndex, int currentIndex,char[] array){
        for(int j = currentIndex-1;j>=lastIndex;j--){
            if(array[j]==array[currentIndex]){
                return j+1;
            }
        }
        return lastIndex;
    }
    
    private boolean emptyString(String s){
        if(s == null || s.length()==0){
            return true;
        }
        return false;
    }

Log in to reply
 

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