์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- ํ์ด์ฌ
- ํฌํฌ์ธํฐ
- ์์ฑํAI
- Python
- sql์ฝํ
- Blazor
- Python3
- GenerativeAI
- ๊ตฌ๊ธํต๋ฉ
- dfs
- ํ์ด์ฌ๊ธฐ์ด100์
- stratascratch
- ๋ฆฌํธ์ฝ๋
- ํ์ด์ฌ์๊ณ ๋ฆฌ์ฆ
- two-pointer
- ์ฝ๋์
- ์๊ณ ๋ฆฌ์ฆ
- LeetCode
- gcp
- medium
- ์ฌ๋ผ์ด๋ฉ์๋์ฐ
- GenAI
- ๋ฆฟ์ฝ๋
- slidingwindow
- codeup
- ๋ํธ์ฝ๋
- ์์ฐ์ด์ฒ๋ฆฌ
- Microsoft
- SQL
- nlp
Archives
- Today
- Total
Tech for good
[Neetcode/Sliding Window] Permutation in String ๋ณธ๋ฌธ
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)์ ์๊ฐ ๋ณต์ก๋๋ก ๋งค์ฐ ๋น ๋ฅด๊ฒ ํด๊ฒฐ ๊ฐ๋ฅ!
'IT > Computer Science' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Leetcode/Sliding Window] 713. Subarray Product Less Than K (0) | 2025.03.08 |
---|---|
[Leetcode/Sliding Window] 1876. Substrings of Size Three with Distinct Characters (0) | 2025.03.03 |
[Leetcode/Sliding Window] 1652. Defuse the Bomb (0) | 2025.03.03 |
[Neetcode 150/Sliding Window] Longest Repeating Character Replacement (0) | 2025.02.26 |
[Leetcode/Sliding Window] 1176. Diet Plan Performance (0) | 2025.02.26 |