Anagrams

来源:互联网 发布:吉威时代待遇知乎 编辑:程序博客网 时间:2024/06/07 06:27

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

Note: All inputs will be in lower-case.


Solution:

class Solution {public:    vector<string> anagrams(vector<string>& strs) {        vector<string> res;        unordered_map<string, int> um;        for(int i = 0; i < strs.size(); ++i)        {            string str = strs[i];            sort(str.begin(), str.end());            if(um.count(str) == 0) um[str] = i;            else            {                if(um[str] >= 0)                {                    res.push_back(strs[um[str]]);                    um[str] = -1;                }                res.push_back(strs[i]);            }        }                return res;    }};


0 0
原创粉丝点击