Anagrams

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

Note: All inputs will be in lower-case.

思路:回文构词法是由颠倒字母顺序而来的单词。主要的特点就是字母个数和种类都一样,只是改变了其顺序。使用map<string,int> amp来保存一个字符串及其出现的位置。首先,从strs第一个字符串开始遍历,使用一变量s来保存,并对其进行排序;2)在amp中查找s,如果没有找到,则记录amp记录s在strs中的位置下标,如果存在,则将第一次出现的字符串保存入result中去,即result.push_back(strs(amp[s]),并且将amp[s]=-1——防止重复查找,然后再将该strs中的字符串保存入result中

class Solution {
public:
    vector<string> anagrams(vector<string> &strs) {
        vector<string> result;
        if(strs.size()<=1)
            return result;
        map<string,int> amp;
        map<string,int>::iterator it;
        for(int i=0;i<strs.size();i++)
        {
            string s=strs[i];
            sort(s.begin(),s.end());
            it=amp.find(s);
            if(it==amp.end())//在amp中没有发现
                amp[s]=i;
            else
            {
                if(amp[s]>=0)
                {
                    result.push_back(strs[amp[s]]);
                    amp[s]=-1;
                }
                result.push_back(strs[i]);
            }
        }
        return result;
    }
};

 

posted @ 2014-05-12 08:44  Awy  阅读(112)  评论(0编辑  收藏  举报