| 1. |
Given an array of strings, you need to remove strings which are anagrams of strings preceding them in the given array. You need to return the remaining strings in sorted order. |
|
Answer» For EXAMPLE, OUTPUT : Explanation : We can simply sort and compare the given two strings to see if they are anagrams or not. We may also use a hashmap to see if a string has appeared or not. Make an auxiliary array to STORE the generated strings, as well as a hashmap to keep track of the string we've FOUND thus far. Then iterate through the array's supplied string, sort the current string, and look it up in the hashmap. If the current text is not found in the hashmap, insert the sorted string arr[i] in the resultant array. After that, sort the array and print each string. Code: void uniqueAnagrams(string arr[], int n){ vector<string> result; //to keep track of already encountered sorted string unordered_set<string> found; for (int i = 0; i < n; i++) { string cur_word = arr[i]; // sorting the current string sort(begin(cur_word), end(cur_word)); // Checking if the current sorted string is present in the data structure already if (found.find(cur_word) == found.end()) { result.push_back(arr[i]); found.insert(cur_word); } } // Sorting the answer vector sort(begin(result), end(result)); // Printing the answer for (int i = 0; i < result.size(); ++i) { cout << result[i] << " "; }}Explanation: In the above code, we created a function uniqueAnagrams, which removes all the duplicate anagrams and prints the sorted array. We take the help of a hashmap to store each visited string in its sorted form. If the current string is not found in the hash map, we push it in the answer vector. At last we sort the answer vector and then display the resultant vector. |
|