Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Sort the strings in the original string array separately, for example, bac --> ABC, and then sort the entire array. If the adjacent strings in the array are equal, then, the two strings in the original array must meet the conditions and be added to the result array. Heap sorting is used to create and sort a single character. Because many repeated elements exist in the string array after a single string is sorted, the string array is sorted by three-way segmentation.
Solution
Class solution {public: vector <string> anagrams (vector <string> & STRs) {vector <string> temp = STRs; int n = temp. size (); vector <string> res; If (n = 0 | n = 1) return res; vector <int> index; For (INT I = 0; I <n; I ++) {index. push_back (I); heap_sort (temp [I]);} quicksort (temp, index, 0, n-1); string flag = temp [index [0]; int COUNT = 1; int I; for (I = 0; I <n-1; I ++) {If (temp [index [I] = temp [index [I + 1]) {res. push_back (STRs [index [I]); count ++;} else {If (count> 1) res. push_back (STRs [index [I]); Count = 1; flag = temp [index [I] ;}} if (count> 1) res. push_back (STRs [index [I]); Return res;} void swap (string & S, int I, Int J) {char temp = s [I]; s [I] = s [J]; s [J] = temp;} void sink (string & S, int Loc, int end) {While (loc <End) {int K = 2 * loc + 1; if (k> end) return; If (k <End & S [k] <s [k + 1]) k ++; If (s [k] <s [loc]) return; swap (S, Loc, k); loc = K ;}} void heap_sort (string & S) {int n = S. length ()-1; for (INT I = (n-1)/2; I> = 0; I --) sink (S, I, n); While (n> 0) {swap (S, 0, n); n --; sink (S, 0, n) ;}} void quicksort (vector <string> & S, vector <int> & Index, int low, int high) {If (low> = high) return; int lT = low; int ht = high; int L = low + 1; string hold = s [index [low]; while (L <= HT) {If (s [index [l] <= hold) Swap (index, Lt ++, l ++); else swap (index, L, HT --);} quicksort (S, index, low, lt-1); quicksort (S, index, HT + 1, high);} void swap (vector <int> & Index, int I, Int J) {int temp = index [I]; index [I] = index [J]; index [J] = temp ;}};
Leetcode -- anagrams