diff --git a/problems/0242.有效的字母异位词.md b/problems/0242.有效的字母异位词.md index 1006ea35..0e5683c7 100644 --- a/problems/0242.有效的字母异位词.md +++ b/problems/0242.有效的字母异位词.md @@ -122,6 +122,21 @@ class Solution { ``` Python: +(版本一) 使用数组 +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + record = [0] * 26 + for i in range(len(s)): + record[ord(s[i]) - ord("a")] += 1 + for i in range(len(t)): + record[ord(t[i]) - ord("a")] -= 1 + for i in range(26): + if record[i] != 0: + return False + return True +``` +(版本二) 使用数组 ```python class Solution: def isAnagram(self, s: str, t: str) -> bool: @@ -138,12 +153,13 @@ class Solution: return True ``` -Python写法二(没有使用数组作为哈希表,只是介绍defaultdict这样一种解题思路): +(版本三) 使用defaultdict ```python +from collections import defaultdict + class Solution: def isAnagram(self, s: str, t: str) -> bool: - from collections import defaultdict s_dict = defaultdict(int) t_dict = defaultdict(int) @@ -156,17 +172,40 @@ class Solution: return s_dict == t_dict ``` -Python写法三(没有使用数组作为哈希表,只是介绍Counter这种更方便的解题思路): +(版本四) 使用字典 ```python -class Solution(object): +class Solution: def isAnagram(self, s: str, t: str) -> bool: - from collections import Counter - a_count = Counter(s) - b_count = Counter(t) - return a_count == b_count + if len(s) != len(t): + return False + + hash_table_s = {} + hash_table_t = {} + + for i in range(len(s)): + hash_table_s[s[i]] = hash_table_s.get(s[i], 0) + 1 + hash_table_t[t[i]] = hash_table_t.get(t[i], 0) + 1 + + return hash_table_s == hash_table_t ``` +(版本五) 使用排序 + +```python +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return sorted(s) == sorted(t) +``` +(版本六) 使用Counter + +```python +from collections import Counter + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) +``` Go: ```go