Skip to content

Commit d30b00f

Browse files
committed
D. J.:
- Added the leetcode problem and solution for 242 Valid Anagram
1 parent 7305566 commit d30b00f

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ This repository contains awesome LeetCode problems and solutions written in Pyth
1616
- [169 Majority Element](https://leetcode.com/problems/majority-element/description/)
1717
- [189 Rotate Array](https://leetcode.com/problems/rotate-array/description/)
1818
- [205 Isomorphic Strings](https://leetcode.com/problems/isomorphic-strings/description/)
19+
- [242 Valid Anagram](https://leetcode.com/problems/valid-anagram/description/)
1920
- [290 Word Pattern](https://leetcode.com/problems/word-pattern/description/)
2021
- [383 Ransom Note](https://leetcode.com/problems/ransom-note/description/)
2122
- [392 Is Subsequence](https://leetcode.com/problems/is-subsequence/description/)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
class Solution:
2+
def isAnagram(self, s: str, t: str) -> bool:
3+
"""
4+
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
5+
6+
An anagram is a word or phrase formed by rearranging the letters of a different word
7+
or phrase, using all the original letters exactly once.
8+
"""
9+
if len(s) != len(t):
10+
return False
11+
12+
counter_s, counter_t = {}, {}
13+
for s_, t_ in zip(s, t):
14+
if s_ not in counter_s:
15+
counter_s[s_] = 1
16+
else:
17+
counter_s[s_] += 1
18+
19+
if t_ not in counter_t:
20+
counter_t[t_] = 1
21+
else:
22+
counter_t[t_] += 1
23+
24+
for k_s, k_t in zip(counter_s, counter_t):
25+
if k_s not in counter_t:
26+
return False
27+
if k_t not in counter_s:
28+
return False
29+
if counter_s[k_s] != counter_t[k_s] or counter_s[k_t] != counter_t[k_t]:
30+
return False
31+
return True

tests/test_242_valid_anagram.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import pytest
2+
3+
from awesome_python_leetcode._242_valid_anagram import Solution
4+
5+
6+
@pytest.mark.parametrize(
7+
argnames=["s", "t", "expected"],
8+
argvalues=[("anagram", "nagaram", True), ("rat", "car", False)],
9+
)
10+
def test_func(s: str, t: str, expected: bool):
11+
is_anagram = Solution().isAnagram(s, t)
12+
assert is_anagram == expected

0 commit comments

Comments
 (0)