Java Solution 5ms O(n) runtime O(1) space two pointers and one Loop


  • 0
    N

    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0) return 0;
        int i=0,j=0,ret=0;
        int[] charIndex = new int[256];
        while(i<s.length()){
            if(charIndex[s.charAt(i)]>j){
                if(i-j > ret) ret = i-j;
                j= charIndex[s.charAt(i)];
            }
            charIndex[s.charAt(i)] = i+1;
            i++;
        }
        return (i-j>ret) ? i-j : ret;
    }
    
    the solution is using two pointers and a map with index as value and skip with the value when the letter is repeated

Log in to reply
 

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