[Algorithm] Longest Substring Without Repeating Characters?

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

Example 1:

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

Example 2:

Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: "pwwkew"
Output: 3
Explanation: 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.

 

Solution:

In the naive approaches, we repeatedly check a substring to see if it has duplicate character. But it is unnecessary. If a substring s_{ij}sij from index ii to j - 1j1 is already checked to have no duplicate characters. We only need to check if s[j]s[j] is already in the substring s_{ij}sij.

To check if a character is already in the substring, we can scan the substring, which leads to an O(n^2)O(n2) algorithm. But we can do better.

By using HashSet as a sliding window, checking if a character in the current can be done in O(1)O(1).

A sliding window is an abstract concept commonly used in array/string problems. A window is a range of elements in the array/string which usually defined by the start and end indices, i.e. [i, j)[i,j) (left-closed, right-open). A sliding window is a window "slides" its two boundaries to the certain direction. For example, if we slide [i, j)[i,j) to the right by 11 element, then it becomes [i+1, j+1)[i+1,j+1) (left-closed, right-open).

Back to our problem. We use HashSet to store the characters in current window [i, j)[i,j) (j = ij=i initially). Then we slide the index jj to the right. If it is not in the HashSet, we slide jj further. Doing so until s[j] is already in the HashSet. At this point, we found the maximum size of substrings without duplicate characters start with index ii. If we do this for all ii, we get our answer.

 

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    let begin = 0, max = 0;
    let hash = new Set();
    
    for (let end = 0; end < s.length; end++) {
        if (hash.has(s[end])) {
            while (s[begin] !== s[end]) {
                // delete chars until the dulpicate one
                hash.delete(s[begin++]);
            }
            // delete dulpicate one
            hash.delete(s[begin++]);
        }
        
        hash.add(s[end])
        max = Math.max(max, hash.size)

    }
    return max;
};

 

posted @ 2019-04-07 02:27  Zhentiw  阅读(348)  评论(0编辑  收藏  举报