[Leetcode] 3. Longest Substring Without Repeating Characters

RexiaN·2025년 11월 28일

주어진 문자열을 검사하여 중복되지 않는 문자들로 이루어진 제일 긴 문자열을 찾아야 한다. 그냥 반복없는 문자만 모으면 안되고 실제 원본 문자열의 일부분이어야(s.lice(i, j) 형태가 될 수 있어야) 한다. 슬라이딩윈도우를 사용한 구간합? 구간중복성? 을 구현하기에 좋은 문제.

function lengthOfLongestSubstring(s: string): number {
    let maxLength = 0;
    let head = 0;
    const charSet = new Set();

    for (let tail = 0; tail < s.length; tail++) {
        while (charSet.has(s[tail])) {
            charSet.delete(s[head]);
            head += 1;
        }

        charSet.add(s[tail]);
        
        maxLength = Math.max(maxLength, tail - head + 1);
    }

    return maxLength;
};

profile
Don't forget Rule No.1

0개의 댓글