Leetcode Group Anagrams
Given an array of strings, group anagrams together. for example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [["ate ", "eat", "tea"], ["nat", "tan"], ["bat"] Note: For the return value, each inner list's elements must follow the lexicographic order. all inputs will be in lower-case. solution: Anagrams refers to the words generated in reverse character order, and abc bca is like this. Therefore, you can sort str [I] characters first during aggregation, and then map the string with hash, then each key corresponds to a str array, and finally the character columns in the hash String getCode (string s) {sort (s. begin (), s. end (); return s;} vector <string> groupAnagrams (vector <string> & strs) {vector <string> results; int size = strs. size (); if (size = 0) return results; if (size = 1) {results. push_back (strs); return results;} map <string, vector <string> head; for (int I = 0; I <size; ++ I) {head [getCode (strs [I])]. push_back (strs [I]);} map <string, vector <string>: Iterator itor = head. begin (), end = head. end (); for (; itor! = End; ++ itor) {sort (itor-> second. begin (), itor-> second. end (); results. push_back (itor-> second);} return results;} the following code is an error in understanding the meaning of the question: at first, I didn't understand Anagrams and thought it was the first list to be connected, solution: the sort array creates a map for the first letter. Note that if it is an empty string, the map will be traversed in the method result during the first scan. In the current itor, if the queue is not blank, it indicates a string starting with the letter, searches for strings starting with the last letter in sequence, and adds tempresult until there is no string starting with the last letter; the queue of the current itor is null, and the vector <string> groupAnagrams (vector <string> & strs) {vector <string> Results; int size = strs. size (); if (size = 0) return results; if (size = 1) {results. push_back (strs); return results;} sort (strs. begin (), strs. end (); vector <string> temp; map <char, queue <int> head; for (int I = 0; I <size; ++ I) {if (strs [I] = "") {temp. push_back (strs [I]);} else head [strs [I] [0]. push (I);} if (temp. size ()> 0) results. push_back (temp); temp. clear (); map <char, queue <int> >:: iterator itor = head. beg In (), end = head. end (); for (; itor! = End;) {if (itor-> second. empty () {++ itor; continue;} int I = itor-> second. front (); itor-> second. pop (); temp. push_back (strs [I]); char ch = strs [I] [0]; char chtail = strs [I]. back (); while (head [chtail]. empty () = false) {int pos = head [chtail]. front (); head [chtail]. pop (); temp. push_back (strs [pos]);} results. push_back (temp); temp. clear ();} return results ;}