-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add longest repeating character replacement solution
- Loading branch information
1 parent
857337b
commit f1f82aa
Showing
1 changed file
with
26 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
from collections import defaultdict | ||
|
||
|
||
class Solution: | ||
def characterReplacement(self, s: str, k: int) -> int: | ||
""" | ||
- Idea: ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ฅผ ์ด์ฉํด ํ์ฌ ์๋์ฐ ๋ด์์ ๊ฐ์ฅ ์์ฃผ ๋ํ๋๋ ๋ฌธ์์ ๊ฐ์๋ฅผ ์ถ์ ํ๋ค. | ||
์ต๋ k๊ฐ์ ๋ฌธ์๋ฅผ ๋ฐ๊ฟจ์ ๋, ๋ชจ๋ ๋ฌธ์๊ฐ ๊ฐ์ ๋ถ๋ถ ๋ฌธ์์ด์ ์ต๋ ๊ธธ์ด๋ฅผ ๊ณ์ฐํ๋ค. | ||
์๋์ฐ๊ฐ ์ ํจํ์ง ์์ผ๋ฉด, ์ผ์ชฝ ํฌ์ธํฐ๋ฅผ ์ด๋์์ผ ์๋์ฐ ํฌ๊ธฐ๋ฅผ ์กฐ์ ํ๋ค. | ||
- Time Complexity: O(n), n์ ๋ฌธ์์ด์ ๊ธธ์ด๋ค. ๊ฐ ๋ฌธ์๋ฅผ ํ๋ฒ์ฉ ์ํํ๊ณ , ์ฌ๋ผ์ด๋ฉ ์๋์ฐ๋ฅผ ์กฐ์ ํ๋ค. | ||
- Space Complexity: O(26) = O(1), ์ฌ๋ผ์ด๋ฉ ์๋์ฐ ๋ด์ ํฌํจ๋ ๋ฌธ์์ ๊ฐ์๋ฅผ ์ธ๊ธฐ ์ํ ๊ณต๊ฐ์ผ๋ก, ์ต๋ ์ํ๋ฒณ ๋ฌธ์์ ๊ฐ์(26๊ฐ)๋งํผ ๋์ด๋ ์ ์๋ค. | ||
""" | ||
result = 0 | ||
counter = defaultdict(int) | ||
left = 0 | ||
|
||
for right in range(len(s)): | ||
counter[s[right]] = counter[s[right]] + 1 | ||
|
||
while (right - left + 1) - max(counter.values()) > k: | ||
counter[s[left]] -= 1 | ||
left += 1 | ||
|
||
result = max(result, right - left + 1) | ||
|
||
return result |