现在的位置: 首页 > 综合 > 正文

Anagrams — leetcode

2018年10月18日 ⁄ 综合 ⁄ 共 576字 ⁄ 字号 评论关闭

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.

算法思路:

将单词进行排序。

用map统计排序后相等的出现次数。

将次数大于1的单词放入结果集。

第1次出现时,因次数最终是否大于1不明郎,将其暂存入另一个数组。

该算法在leetcode上实际执行时间为67ms。

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> ans;
        unordered_map<string, int> count;
        vector<pair<string, int> > first;

        for (int i=0; i<strs.size(); i++) {
                string tmp = strs[i];
                sort(tmp.begin(), tmp.end());
                if (count[tmp]++)
                        ans.push_back(strs[i]);
                else
                        first.push_back(make_pair(tmp, i));
        }

        for (auto i: first) {
                if (count[i.first] > 1)
                        ans.push_back(strs[i.second]);
        }

        return ans;
    }
};

抱歉!评论已关闭.