171. 乱序字符串
给出一个字符串数组S,找到其中所有的乱序字符串(Anagram)。如果一个字符串是乱序字符串,那么他存在一个字母集合相同,但顺序不同的字符串也在S中。
样例
对于字符串数组 ["lint","intl","inlt","code"]
返回 ["lint","inlt","intl"]
挑战
What is Anagram?
- Two strings are anagram if they can be the same after change the order of characters.
注意事项
所有的字符串都只包含小写字母
解题思路:
既然是乱序的字符串,那么排序以后应该是相等的。
用一个hash表保存所有的元素,排序后相同的元素放在与一个列表中。
遍历hash表,列表中元素个数大于1,则存在乱序字符串。
class Solution:
"""
@param strs: A list of strings
@return: A list of strings
"""
def anagrams(self, strs):
# write your code here
hashmap = {}
res = []
for item in strs:
sort_item = ''.join(sorted(item))
if sort_item in hashmap:
hashmap[sort_item].append(item)
else:
hashmap[sort_item] = [item]
for key in hashmap:
if len(hashmap[key]) > 1:
res += hashmap[key]
return res