LeetCode算法題之Anagrams

問題描述:
Given an array of strings, return all groups of strings that are
anagrams. Note: All inputs will be in lower-case.

Anagrams指的是具有如下特性的兩個單詞:在這兩個單詞當中,每一個英文字母(不區分大小寫)所出現的次數都是相同的。
例如,“Unclear”和“Nuclear”、“Rimon”和“MinOR”都是Anagrams。編寫一個程序,輸入兩個單詞,然後判斷一下,這兩個單詞是否是Anagrams。每一個單詞的長度不會超過80個字符,而且是大小寫無關的。

本題中輸入的字符串都是小寫的,而且此題返回值要求是vector所以只能有一組anagrams。

解題思路:
先將所有的單詞按英文字母順序排序,設置一個map,排列後的單詞作爲map的key,值是vector類型,存放的剛好是互爲anagrams的若干單詞。

class Solution
{
public:
    vector<string> anagrams(vector<string> &strs)
    {
        vector<string> result;
        map<string, vector<string> > countMap;
        if(strs.empty())
            return result;
        if(strs.size() == 1)
            return result;
        vector<string> strs_duplication;
        strs_duplication = strs;
        for(size_t i=0; i<strs_duplication.size(); i++)
        {
            string tempString = strs_duplication[i];
            //此處是大小寫轉換,針對本題可忽略
            for(unsigned int j=0; j<tempString.length(); j++)
            {
                if(tempString[j]>=65&&tempString[j]<=90)
                    tempString[j]=(char)(tempString[j]+32);
            }
            //使用sort函數排序
            char* s;
            const int len = tempString.length();
            s =new char[len+1];
            strcpy(s,tempString.c_str());
            sort(s,s+tempString.length());
            countMap[s].push_back(tempString);
        }

        for(map<string, vector<string> >::iterator iter = countMap.begin(); iter != countMap.end(); iter++)
        {
            if ((iter->second).size() > 1)
            {
                for(unsigned int i = 0; i < (iter->second).size(); i++)
                    result.push_back((iter->second)[i]);
            }
        }
        return result;
    }
};
發佈了47 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章