Update 0242.有效的字母异位词.md

This commit is contained in:
程序员Carl
2023-05-07 09:47:01 +08:00
committed by GitHub
parent f97ff3a1be
commit 3f45b56cef

View File

@ -122,21 +122,7 @@ 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:
@ -153,59 +139,7 @@ class Solution:
return True
```
(版本三) 使用defaultdict
```python
from collections import defaultdict
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
s_dict = defaultdict(int)
t_dict = defaultdict(int)
for x in s:
s_dict[x] += 1
for x in t:
t_dict[x] += 1
return s_dict == t_dict
```
(版本四) 使用字典
```python
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
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