Given an array of strings, group anagrams together.
For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"]
,
Return:
[
["ate", "eat","tea"],
["nat","tan"],
["bat"]
]
Note: All inputs will be in lower-case.
这个题没太懂该怎么输出,它给的返回类型是多维数组...看讨论貌似只需要把与自己排序字符串相同的放在一起就可以了。
于是,我的代码:
class Solution {
public:
vector<string> groupAnagrams(vector<string>& strs) {
vector<int> sum;
string arr;
for(int i = 0; i < (int)strs.size(); i++) { // O(n*m)
sum.push_back(0);
arr = strs[i];
for(int j = 0; arr[j] != '\0'; j++)
sum[i] += (int)arr[j];
}
vector<string> mapstrs;
int len = (int)strs.size();
for(int i = 0; i < len;) { // O(n)
int temp = sum[i];
for(int j = 0; j < len; j++)
if(temp == sum[j]) {
mapstrs.push_back(strs[j]);
int k = j;
while(k + 1 < len) {
strs[k] = strs[k + 1];
sum[k] = sum[k + 1];
k++;
}
len = k;
}
}
return mapstrs;
}
};
时间复杂度为O(n*m),其中n为字符串个数,m为最长字符串中字符的个数。
但它给的例子是这样的:
input: ["eat","tea","tan","ate","nat","bat"]
answer: [["bat"],["nat","tan"],["ate","eat","tea"]]
所以,完全错误,并没有AC。这里考点是hash。。。所以,没必要这么麻烦。
讨论区看到一个python的solution,感觉不错:
# https://leetcode.com/problems/group-anagrams/discuss/19202
class Solution:
def groupAnagrams(self, strs):
d = {}
for w in sorted(strs):
key = tuple(sorted(w))
d[key] = d.get(key, []) + [w]
return d.values()
strs = ['dog','cat','god','tac','atc','oob']
so = Solution()
print(so.groupAnagrams(strs))