LeetCode 3.

Tags:

Question

Given a string s, find the length of the longest 
substring without repeating characters.

Example 1:

Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.

Complexity

  • Time complexity: O(nlogn)

  • Space complexity: O(n)

Code

class Solution {
    public int lengthOfLongestSubstring(String s) {
        boolean[] exist = new boolean[200]; //ascii

        int l = 0, r = 0;
        int ans = 0;
        while (r < s.length()) {
            int c = (int) s.charAt(r);
            while (l < r && exist[c]) {
                exist[(int) s.charAt(l++)] = false;
            }
            exist[c] = true;
            ans = Math.max(ans, r - l + 1);
            r++;
        }

        return ans;
    }
}

Check out the description of this problem at LC 3.