首页 > 代码库 > Anagrams

Anagrams

这题折腾主要是因为对于这个anagram的定义理解有误,参看维基页面:

An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once; for example Torchwood can be rearranged into Doctor Who. Someone who creates anagrams may be called an "anagrammatist".[1] The original word or phrase is known as thesubject of the anagram.

Any word or phrase that exactly reproduces the letters in another order is an anagram. However, the goal of serious or skilled anagrammatists is to produce anagrams that in some way reflect or comment on the subject. Such an anagram may be a synonym or antonym of its subject, a parody, a criticism, or praise; e.g. William Shakespeare = I am a weakish speller

Another example is "silent" which can be rearranged to "listen". The two can be used in the phrase, "Think about it, SILENT and LISTEN are spelled with the same letters". (To mean "the quieter you become, the more you can hear").

简单解释就是说,两个单词word1, word2,构成他们的字符个数和种类都相同,那就是满足anagram。

实际实现就是,如果word2能够通过调整字符顺序得到word1,那就成立了。

    vector<string> anagrams(vector<string> &strs) {    map<string, int> table;	for (auto it = strs.begin(); it != strs.end(); it++){		string s = *it;		sort(s.begin(), s.end());		if (table.find(s) == table.end()){			table[s] = 1;		}		else {			table[s]++;		}	}	vector<string> result;	for (auto it = strs.begin(); it != strs.end(); it++){		string s = *it;		sort(s.begin(), s.end());		if (table[s] > 1)			result.push_back(*it);	}	return result;    }

  

Anagrams