File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -20,6 +20,36 @@ All inputs will be in lower-case
20
20
21
21
题 [ Two Strings Are Anagrams] ( http://algorithm.yuanbin.me/zh-hans/string/two_strings_are_anagrams.html ) 的升级版,容易想到的方法为使用双重` for ` 循环两两判断字符串数组是否互为变位字符串。但显然此法的时间复杂度较高。还需要 $$ O(n) $$ 的数组来记录字符串是否被加入到最终结果中。
22
22
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
+
23
53
### C++
24
54
25
55
``` c++
You can’t perform that action at this time.
0 commit comments