[LeetCode系列] 變序詞查找問題(Anagrams)

給定一系列詞, 找出其中所有的變序詞組合.

Note: 變序詞 - 組成字符完全相同但次序不同的單詞. 如dog和god, ate和eat.

 

算法描述: 使用map<string, vector<string> >存儲所有的結果. 最後將map中size > 1的vector<string>插入到結果中.

 

代碼:

 1 class Solution {
 2 public:
 3     vector<string> anagrams(vector<string> &strs) {
 4         vector<string> res;
 5         map<string, vector<string> > rec;
 6         if (strs.size() == 0) return res;
 7         
 8         for (string s : strs) {
 9             string ts(s);
10             sort(ts.begin(), ts.end());
11             rec[ts].push_back(s);
12         }
13         
14         for (auto map : rec) {
15             if (map.second.size() > 1)
16                 res.insert(res.end(), map.second.begin(), map.second.end());
17         }
18         
19         return res;
20     }
21 };

其中map.second代表的是map中的value, 即vector<string>.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章