[리트코드] Minimum Window Substring

박형진·2021년 12월 29일
0

https://leetcode.com/problems/minimum-window-substring/


1. 전체 코드

from collections import Counter

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        need = Counter(t)
        missing = len(t)
        left = start = end = 0
        for right, char in enumerate(s, 1):  # 시작인덱스가 0이아닌 1, (right=1, char=s[0])
            if need[char] > 0:
                missing -= 1
            need[char] -= 1
            if missing == 0:
                # t에 들어있는 문자열이 시작점이 되도록 left 이동 (불필요한 문자들 제거)
                while left < right and need[s[left]] != 0:
                    need[s[left]] += 1
                    left += 1
                # not end -> 처음 진입 조건 end = 0
                # right - left <= end - start -> 더 짧은 문자열 발견
                if not end or right - left <= end - start:
                    start, end = left, right
                    need[s[left]] += 1
                    missing += 1  # 현재 s[left] 는 t에 들어있는 문자임이 보장된 상탵
                    left += 1  # 다음 문자열로 이동
        return s[start:end]

슬라이딩 윈도우 문제의 경우 투 포인터를 사용하기 위해 인덱스를 통한 접근을 먼저 생각해보자

profile
안녕하세요!

0개의 댓글