[Leetcode] Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
这题先得知道啥叫Anagrams,知道后其实很简单。
首先简单介绍一下Anagram(回文构词法)。Anagrams是指由颠倒字母顺序组成的单词,比如“dormitory”颠倒字母顺序会变成“dirty room”,“tea”会变成“eat”。
回文构词法有一个特点:单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。
For example:
Input: ["tea","and","ate","eat","den"]
Output: ["tea","ate","eat"]
1 class Solution { 2 public: 3 vector<string> anagrams(vector<string> &strs) { 4 string s; 5 map<string, int> anagram; 6 vector<string> res; 7 for (int i = 0; i < strs.size(); ++i) { 8 s = strs[i]; 9 sort(s.begin(), s.end()); 10 if (anagram.find(s) == anagram.end()) { 11 anagram[s] = i; 12 } else { 13 if (anagram[s] >= 0) { 14 res.push_back(strs[anagram[s]]); 15 anagram[s] = -1; 16 } 17 res.push_back(strs[i]); 18 } 19 } 20 return res; 21 } 22 };