Anagrams - LeetCode
题目:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
分析:
首先解释anagrams的含义:anagram解释为回文构词法,即单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。例如:eat ,eta ,tea 都是满足回文构词法的。
所以我们利用了两个hash表,首先把单词变成字母表顺序,dic是记录单词的出现位置,而count记录了单词的出现次数,因为如果出现两次单词,我们需要在最后加上最后一次出现的那个单词。
代码:
class Solution:
# @param strs, a list of strings
# @return a list of strings
def anagrams(self, strs):
dic = {}
count = {}
res = []
for i in range(len(strs)):
temp = "".join(sorted(strs[i]))
if temp not in dic:
dic[temp] = i
count[temp] = 1
else:
res.append(strs[dic[temp]])
dic[temp] = i
count[temp] += 1
for i in count.keys():
if count[i] != 1:
res.append(strs[dic[i]])
return res