Java solution, with O(n) time and O(1) space


  • 0
    L

    public int lengthOfLongestSubstring(String s) {
    if (s == null || s.length() == 0) {
    return 0;
    }

        int[] freq = new int[256];
        char[] array = s.toCharArray();
        
        int i = 0;
        int j = 0;
        
        int len = 0;
        
        while (j < array.length) {
            if (freq[array[j]] == 0) {
                freq[array[j]]++;
                j++;
                
            } else {
                len = Math.max(len, j - i);
                freq[array[i]]--;
                i++;
            } 
        }
        
        return Math.max(len, j - i);
        
    }

Log in to reply
 

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