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

Leetcode Anagrams

2019年03月10日 ⁄ 综合 ⁄ 共 622字 ⁄ 字号 评论关闭

题目:

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

Note: All inputs will be in lower-case.

解题:

这题目真心没说明白,看别人博客才懂的题意,看懂以后基本就可以搞了。

我直接两个map搞

第一次把单词映射到排序后的单词,第二次把排序后的单词映射成数字,每映射成数字一次,数字+1。

最后输出两次map后大于1的即可

代码:

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        int nr[strs.size()];
        memset(nr, 0, sizeof(nr));
        map<string, string> mp;
        map<string, int> mpCnt;
        for(int i = 0; i < strs.size(); i ++) {
            string tmp = strs[i];
            sort(tmp.begin(), tmp.end());
            mp[strs[i]] = tmp;
            if(mpCnt.find(tmp) == mpCnt.end())
                mpCnt[tmp] = 1;
            else
                mpCnt[tmp] ++;
        }
        vector<string> ans;
        for(int i = 0; i < strs.size(); i ++) {
            if(mpCnt[mp[strs[i]]] > 1)
                ans.push_back(strs[i]);
        }
        return ans;
    }
};

抱歉!评论已关闭.