7ms Java Solution using two pointers O(n) time complexity O(n) space Complexity


  • 0
    N

    public int lengthOfLongestSubstring(String s) {
        if(s.length()==0) return 0;
        int i=0,j=0,ret=0;
        boolean[] existed = new boolean[256];
        while(i<s.length()){
            if(existed[s.charAt(i)]){
                if(i-j > ret) ret = i-j;
                while(s.charAt(j)!=s.charAt(i)){
                    existed[s.charAt(j)] = false;    
                    j++;
                }
                j++;
            }
            existed[s.charAt(i)] = true;
            i++;
        }
        return (i-j>ret) ? i-j : ret;
    }
    

  • 0
    N

    O(1) space complexity


Log in to reply
 

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