Notice:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
For example:
Input:["Tea", "and", "ate", "eat", "den"]
Output:["Tea", "ate", "eat"]
Interface:Vector<String>Anagrams(Vector<String>&STRs);
Solution:
Words with different sequences composed of the same letters must be the same after sorting, so they can be stored in the map, and finally the values greater than 1 can be retrieved from the map, that is, the letter "people" composed of the same letters"
For example, ["ate", "tea", "AET", "eat", "HgT", "gf", "ATG ", "gat"] for this container, we first sort the ATE dictionary, convert it to AET, and then put it into map. The map structure here is
Map <string, vector <string>
After 7 words are traversed, the map structure is as follows:
Key value [0] value [1] value [2] value [3]
AET ate tea AET eat
Ght HgT
FG GF
Agt atg gat
After traversing the map, put the words "who" with the number of values greater than 1 into the res array,
The anagrams In the res Array
Two groups of anagrams will be output here
1 Class Solution { 2 Public : 3 Vector < String > Anagrams (vector < String > & STRs ){ 4 Map < String , Vector < String > M; 5 Vector < String > Res; 6 For ( Int I = 0 ; I <STRs. Size (); I ++ ){ 7 String S = STRs [I]; 8 Sort (S. Begin (), S. End ()); // Sort 9 M [s]. push_back (STRs [I]); // Insert Map 10 } 11 12 For (Map < String , Vector < String >>:: Iterator I = M. Begin (); I! = M. End (); I ++ ){ 13 If (I-> second). Size ()> 1 ) 14 For ( Int It =0 ; It <(I-> second). Size (); It ++ ) 15 Res. push_back (I-> second) [it]); // Output 16 } 17 Return Res; 18 } 19 };
PS: You must have a deep understanding of the map usage in STL. The key-value can be of various types, including the container type. Size () and other built-in functions are also common.