Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3. Longest Substring Without Repeating Characters #140

Open
Tcdian opened this issue May 2, 2020 · 1 comment
Open

3. Longest Substring Without Repeating Characters #140

Tcdian opened this issue May 2, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented May 2, 2020

3. 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.
@Tcdian
Copy link
Owner Author

Tcdian commented May 2, 2020

Solution

  • JavaScript Solution
/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function(s) {
    const cache = new Set();
    let result = 0;
    for (let l = 0, r = 0; r < s.length; r++) {
        if (!cache.has(s[r])) {
            cache.add(s[r]);
        } else {
            while (s[l] !== s[r]) {
                cache.delete(s[l++]);
            }
            l++;
        }
        result = Math.max(result, r - l + 1);
    }
    return result;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant