mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
Update 0242.有效的字母异位词.md
This commit is contained in:
@ -122,21 +122,7 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
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
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def isAnagram(self, s: str, t: str) -> bool:
|
def isAnagram(self, s: str, t: str) -> bool:
|
||||||
@ -153,59 +139,7 @@ class Solution:
|
|||||||
return True
|
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:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
Reference in New Issue
Block a user