Longest Substring Without Repeating Characters

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


Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Time complexity : O(2n) = O(n)O(2n)=O(n). In the worst case each character will be visited twice by ii and jj.

Space complexity : O(min(m, n))O(min(m,n)). Same as the previous approach. We need O(k)O(k) space for the sliding window, where kk is the size of the Set. The size of the Set is upper bounded by the size of the string nn and the size of the charset/alphabet mm.


public class Solution {
    public int lengthOfLongestSubstring(String s) {
        if ( s == null || s.length() == 0) return 0;
        HashSet<Character> set = new HashSet<Character>();
        int j = 0;
        int res = 0;
        for ( int i = 0; i < s.length(); i++){
            while(j < s.length() && (! set.contains(s.charAt(j)))){
               set.add(s.charAt(j));
               j++;

            }
            res = Math.max(res, j - i);
            if (j == s.length()) {
                break;
            }
            set.remove(s.charAt(i));
        }
        return res;
    }
}

results matching ""

    No results matching ""