본문 바로가기

리트코드/midium

[리트코드] 3. Longest Substring Without Repeating Characters - js (슬라이딩 윈도우)

반응형

1. 문제

https://leetcode.com/problems/longest-substring-without-repeating-characters/description/

 

Longest Substring Without Repeating Characters - LeetCode

Can you solve this real interview question? Longest Substring Without Repeating Characters - 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 "

leetcode.com

2. 코드

 이 문제는 슬라이딩 윈도우와 중복을 허용하지 않는 객체인 Set을 사용해야 한다.

/**
 * @param {string} s
 * @return {number}
 */
var lengthOfLongestSubstring = function (s) {
    let set = new Set();
    let left = 0;
    let maxSize = 0;

    if (s.length <= 0) return s.length;

    for (let i = 0; i < s.length; i++) {
        while (set.has(s[i])) {
            set.delete(s[left]);
            left++;
        }
        set.add(s[i]);
        maxSize = Math.max(maxSize, i - left + 1);
    }
    return maxSize;
}

 

참고한 해설)

https://leetcode.com/problems/longest-substring-without-repeating-characters/solutions/2694302/js-98-sliding-window-with-exlanation/

반응형