Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

  • Time: O(n)
  • Space: O(1)
public int lengthOfLongestSubstring(String s) {
    int[] count = new int[256];
    int maxLen = 0, j = 0;
    for (int i = 0; i < s.length(); i++) {
        if (count[s.charAt(i)] > 0) {
            j = Math.max(j, count[s.charAt(i)]);
        }
        count[s.charAt(i)] = i + 1;
        maxLen = Math.max(maxLen, i - j + 1);
    }
    return maxLen;
}

results matching ""

    No results matching ""