IT/Computer Science
[Neetcode/Sliding Window] Permutation in String
Diana Kang
2025. 3. 3. 02:00
https://neetcode.io/problems/permutation-string
NeetCode
neetcode.io
๐ ํด๊ฒฐ ์ ๋ต
์ด ๋ฌธ์ ๋ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ(Sliding Window) + ํด์๋งต(๋์ ๋๋ฆฌ) ํ์ฉ์ผ๋ก O(n)์ ํด๊ฒฐํ ์ ์๋ค.
- s1์ ๋ชจ๋ ๋ฌธ์ ๋น๋ ์๋ฅผ ๊ณ์ฐ (char_count_s1).
- s2์์ ๊ธธ์ด๊ฐ len(s1)์ธ ์๋์ฐ๋ฅผ ์ด๋ํ๋ฉฐ ๊ฐ์ ๋น๋ ์๋ฅผ ๊ฐ๋์ง ๋น๊ต (char_count_window).
- ์ฒซ ๋ฒ์งธ ์๋์ฐ ํ์ธ ํ ํ ์นธ์ฉ ์ด๋ํ๋ฉฐ ๊ฒ์ฌ
- ๋ง์ฝ ๋์ผํ ๋น๋ ์๋ฅผ ๊ฐ์ง๋ ๊ตฌ๊ฐ์ด ์๋ค๋ฉด True ๋ฐํ.
class Solution:
def checkInclusion(self, s1: str, s2: str) -> bool:
n, m = len(s1), len(s2)
if n > m: # s1์ด s2๋ณด๋ค ๊ธธ๋ฉด ๋ถ๊ฐ๋ฅ
return False
# 1๏ธโฃ s1์ ๋ฌธ์ ๋น๋์ ๊ณ์ฐ
char_count_s1 = Counter(s1)
# 2๏ธโฃ s2์์ ์ฒ์ `n` ๊ธธ์ด์ ์๋์ฐ ๋ฌธ์ ๋น๋์ ๊ณ์ฐ
char_count_window = Counter(s2[:n])
# 3๏ธโฃ ์ฒซ ๋ฒ์งธ ์๋์ฐ๊ฐ ์ ๋ต์ธ์ง ํ์ธ
if char_count_window == char_count_s1:
return True
# 4๏ธโฃ ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ์ด๋
for i in range(n, m):
# ์๋ก ์ถ๊ฐ๋ ๋ฌธ์ => ์๋ก์ด ๋ฌธ์ ์ถ๊ฐ
char_count_window[s2[i]] += 1
# ์ ๊ฑฐ๋๋ ๋ฌธ์ => ์ผ์ชฝ ๋ ๋ฌธ์ ์ ๊ฑฐ
char_count_window[s2[i - n]] -= 1
# ํ์ฌ ์๋์ฐ ๋น๋์์ s1 ๋น๋์ ๋น๊ต
if char_count_window == char_count_s1:
return True
return False
โณ ์๊ฐ ๋ณต์ก๋ ๋ถ์
- ์ด๊ธฐ Counter(s1), Counter(s2[:n]) ๊ณ์ฐ: O(n)
- ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ์ด๋: O(m - n)
- ์ด ์๊ฐ ๋ณต์ก๋: O(n) + O(m - n) = O(m)
๐ก ์ฆ, O(m)์ ์๊ฐ ๋ณต์ก๋๋ก ๋งค์ฐ ๋น ๋ฅด๊ฒ ํด๊ฒฐ ๊ฐ๋ฅ!