Skip to content

Commit 7d5bba4

Browse files
committed
Merge pull request billryan#79 from yehjames/patch-6
add a solution of python
2 parents e31a247 + 59146b4 commit 7d5bba4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

zh-hans/string/anagrams.md

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,36 @@ All inputs will be in lower-case
2020

2121
[Two Strings Are Anagrams](http://algorithm.yuanbin.me/zh-hans/string/two_strings_are_anagrams.html) 的升级版,容易想到的方法为使用双重`for`循环两两判断字符串数组是否互为变位字符串。但显然此法的时间复杂度较高。还需要 $$O(n)$$ 的数组来记录字符串是否被加入到最终结果中。
2222

23+
### Python
24+
25+
```python
26+
class Solution:
27+
# @param strs: A list of strings
28+
# @return: A list of strings
29+
# @return: A list of strings
30+
def anagrams(self, strs):
31+
32+
if len(strs) < 2 :
33+
return strs
34+
result=[]
35+
visited=[False]*len(strs)
36+
for index1,s1 in enumerate(strs):
37+
hasAnagrams = False
38+
for index2,s2 in enumerate(strs):
39+
if index2 > index1 and not visited[index2] and self.isAnagrams(s1,s2):
40+
result.append(s2)
41+
visited[index2]=True
42+
hasAnagrams = True
43+
if not visited[index1] and hasAnagrams:
44+
result.append(s1)
45+
return result
46+
47+
def isAnagrams(self, str1, str2):
48+
if sorted (str1) == sorted(str2):
49+
return True
50+
return False
51+
```
52+
2353
### C++
2454

2555
```c++

0 commit comments

Comments
 (0)