Anagrams(hash表)

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

Note: All inputs will be in lower-case.

1.概念,首先简单介绍一下Anagram(回文构词法)。

Anagrams是指由颠倒字母顺序组成的单词,比如“dormitory”颠倒字母顺序会变成“dirty room”,“tea”会变成“eat”。

回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。

For example:

Input:  ["tea","and","ate","eat","den"]

Output:   ["tea","ate","eat"]

2.代码,其实就是把每个字符给排序,然后去和hash表存储的比较,时间复杂度O(n*mlogm),m为字符串容器中最大字符串的长度:

class Solution{
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> res;
        if(strs.size()==0) 
            return res;
        map<string,int> m;
        for (int i=0;i<strs.size();++i)
        {
            string s=strs[i];
            sort(s.begin(),s.end());
            if(m.count(s)==0){
                m[s]=i;
            }else{
                res.push_back(strs[i]);
                if(m[s]!=-1){res.push_back(strs[m[s]]);m[s]=-1;}
            }
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/fightformylife/p/4223958.html