[Leetcode] 438. Find All Anagrams in a String
[Leetcode] 438. Find All Anagrams in a String

[Leetcode] 438. Find All Anagrams in a String

์–ธ์–ด
Python
C
๋‚œ์ด๋„
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
๋‹ค์‹œ ํ’€์–ด๋ณด๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•
์ž‘์„ฑ์ž
๋ฐ•์šฉ์„ฑ๋ฐ•์šฉ์„ฑ
์ƒ์„ฑ ์ผ์‹œ
2024๋…„ 08์›” 02์ผ
floatFirstTOC: right

๐Ÿ–ฅ๏ธย ์‹œ์ž‘ํ•˜๋ฉฐ

s ๋ฌธ์ž์—ด์— p ๋ฌธ์ž์—ด์ด ํฌํ•จ๋˜์–ด ์žˆ๋Š”, ์ฆ‰ ์• ๋„ˆ๊ทธ๋žจ์˜ ์‹œ์ž‘์ ์˜ ์ธ๋ฑ์Šค๋ฅผ ์ถœ๋ ฅํ•˜๋Š” ๋ฌธ์ œ๋‹ค. ์—ฌ๊ธฐ์„œ p ์˜ ์ˆœ์„œ๋Š” ๊ณ ๋ คํ•˜์ง€ ์•Š๋Š”๋‹ค.
ย 
๋ฌธ์ œ์˜ s = "cbaebabacd" ์™€ p = "abc" ๋กœ ์˜ˆ์‹œ๋ฅผ ๋“ค์–ด๋ณด์ž.
  1. ์ดˆ๋ฐ˜ i ๊ฐ€ p_length ๋ณด๋‹ค ์ž‘์„ ๋•Œ๊นŒ์ง€:
    1. if s_count == p_count: res.append(i - p_length + 1)
      ์œ„ if๋ฌธ์€ ์ง€๋‚˜์น˜๊ณ  ์•„๋ž˜ ๊ตฌ๋ฌธ์— ๊ฑธ๋ฆฐ๋‹ค. s_count ์นด์šดํ„ฐ์™€ p_count ์นด์šดํ„ฐ๊ฐ€ ๊ฐ™๋‹ค๋ฉด res ์— ์‹œ์ž‘ ์ธ๋ฑ์Šค๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
      • ์—ฌ๊ธฐ์„œ "cba" ์™€ "abc" ๊ฐ€ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์— 0์ด res์— ์ถ”๊ฐ€๋จ
      ย 
  1. ์ดํ›„ ์ดˆ๋ฐ˜ i ๊ฐ€ p_length ๋ณด๋‹ค ํฌ๋ฉด :
    1. if s_count[s[i - p_length]] == 1: # ์ด์ „ ๋ฃจํ”„์˜ ๋งจ ์™ผ์ชฝ ๋ฌธ์ž ์‚ญ์ œ del s_count[s[i - p_length]] else: s_count[s[i - p_length]] -= 1
      ์Šฌ๋ผ์ด์Šค ์œˆ๋„์šฐ์˜ ํฌ๊ธฐ๊ฐ€ ์ปค์ง€๋Š” ๊ฒƒ์„ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด s_count[s[i - p_length]] == 1 ์กฐ๊ฑด์œผ๋กœ ์ด์ „ ๋ฃจํ”„์—์„œ์˜ ๋งจ ์™ผ์ชฝ ๋ฌธ์ž๋ฅผ ์ œ๊ฑฐํ•˜๋„๋ก ํ•œ๋‹ค.
      ๋˜ํ•œ ์ค‘๋ณต ๋ฌธ์ž์—ด์ด ๋“ค์–ด๊ฐ€ ์žˆ์„ ๊ฐ€๋Šฅ์„ฑ์ด ์žˆ์œผ๋ฏ€๋กœ ๋งŒ์ผ if๋ฌธ์— ๊ฑธ๋Ÿฌ์ง€์ง€ ์•Š์•˜๋‹ค๋ฉด ๊ทธ๋ƒฅ -1 ์ฒ˜๋ฆฌ๋ฅผ ํ•ด ์ค€๋‹ค.
      ย 
      • ์—ฌ๊ธฐ์„œ i = 3 ์ด๊ณ  p_length = 3 ์ด๋ฏ€๋กœ s[i - p_length] ๋Š” "c"
      • s_count์˜ "c"์— ๋Œ€ํ•œ ๋นˆ๋„๋ฅผ ๊ฐ์†Œ์‹œํ‚จ๋‹ค.
ย 

โš™๏ธย Python

from collections import Counter from typing import List class Solution: def findAnagrams(self, s: str, p: str) -> List[int]: res = [] p_count = Counter(p) s_count = Counter() p_length = len(p) for i in range(len(s)): s_count[s[i]] += 1 if i >= p_length: if s_count[s[i - p_length]] == 1: del s_count[s[i - p_length]] else: s_count[s[i - p_length]] -= 1 if s_count == p_count: res.append(i - p_length + 1) return res if __name__ == "__main__": sol = Solution() print(sol.findAnagrams("cbaebabacd", "abc")) # [0, 6]
ย 

๐Ÿ“Œย ์†Œ๊ฐ

๋Œ“๊ธ€

guest