|
1 | 1 | """
|
2 |
| -Inputs: |
| 2 | +Inputs: two strings : s, t |
3 | 3 |
|
4 |
| -Outputs: |
| 4 | +Outputs: t ๊ฐ s์ anagram์ธ์ง์ ๋ํ ์ฌ๋ถ |
5 | 5 |
|
6 | 6 | Constraints:
|
7 | 7 |
|
8 |
| -Time Complexity: |
| 8 | +1 <= s.length, t.length <= 5 * 10^4 |
| 9 | +s and t consist of lowercase English letters. |
9 | 10 |
|
10 |
| -Space Complexity: |
| 11 | +Time Complexity: O(n) |
| 12 | +
|
| 13 | +๊ฐ ๋ฌธ์๋ค์ ๋ฑ์ฅ ํ์๋ง ๊ฐ์ผ๋ฉด ๋์ง ์๋? |
| 14 | +
|
| 15 | +s์ Counter ์์ฑ |
| 16 | +t์ Counter ์์ฑ |
| 17 | +
|
| 18 | +t Counter์ keys() ๋๋ฉด์, |
| 19 | +ํด๋น ๊ฐ์ด s Counter ๋ฐฐ์ด key์ ์๋์ง, ๊ทธ๋ฆฌ๊ณ ๊ทธ key์ value๊ฐ์ด ์๋ก ๊ฐ์์ง ์ฒดํฌ |
| 20 | +
|
| 21 | +Space Complexity: O(n) |
11 | 22 |
|
12 | 23 | """
|
13 | 24 |
|
| 25 | +# ์ฒซ ์ฝ๋ |
| 26 | + |
| 27 | +from collections import defaultdict |
| 28 | + |
| 29 | + |
| 30 | +class Solution: |
| 31 | + def isAnagram(self, s: str, t: str) -> bool: |
| 32 | + s_dict, t_dict = defaultdict(int), defaultdict(int) |
| 33 | + |
| 34 | + for ch in s: |
| 35 | + s_dict[ch] += 1 |
| 36 | + |
| 37 | + for ch in t: |
| 38 | + t_dict[ch] += 1 |
| 39 | + |
| 40 | + for key in t_dict.keys(): |
| 41 | + if key not in t_dict or t_dict[key] != s_dict[key]: |
| 42 | + return False |
| 43 | + |
| 44 | + return True |
| 45 | + |
| 46 | +# ๋ฐ๋ก ๋ฐ์ |
| 47 | + |
| 48 | +# s = "ab", t = "a" |
| 49 | +# ์ด๋ ํ ๋ฌธ์์ด์ ๊ธฐ์ค์ผ๋ก ์ธ๋ฉด ์๋๋ ๊ฒ ๊ฐ๋ค |
| 50 | +# ๋ count ์ฌ์ ์ ๋ชจ๋ ๋์์ผํ ๋ฏ. t keys()๋ฅผ ๊ธฐ์ค์ผ๋ก๋ง ๋๋ฉด true๊ฐ ๋์๋ฒ๋ฆผ. ๋ต์ false์ธ๋ฐ |
| 51 | + |
| 52 | + |
| 53 | +from collections import defaultdict |
| 54 | + |
| 55 | + |
| 56 | +class Solution: |
| 57 | + def isAnagram(self, s: str, t: str) -> bool: |
| 58 | + s_dict, t_dict = defaultdict(int), defaultdict(int) |
| 59 | + |
| 60 | + for ch in s: |
| 61 | + s_dict[ch] += 1 |
| 62 | + |
| 63 | + for ch in t: |
| 64 | + t_dict[ch] += 1 |
| 65 | + |
| 66 | + for key in t_dict.keys(): |
| 67 | + if key not in s_dict or t_dict[key] != s_dict[key]: |
| 68 | + return False |
| 69 | + |
| 70 | + for key in s_dict.keys(): |
| 71 | + if key not in t_dict or t_dict[key] != s_dict[key]: |
| 72 | + return False |
| 73 | + |
| 74 | + return True |
14 | 75 |
|
0 commit comments