[LeetCode] Anagrams
Anagrams
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Solution:
Anagrams refers to the two words with the same length and different numbers of characters. For example, cinema and iceman are modified characters.
To determine whether two strings (with the same length) are modified, you can count each character in one string, traverse another string, and subtract the corresponding characters. If a negative number is displayed for the count of a character, it is not an unaltered word. Otherwise, they are an unaltered word. The time complexity of this method is O (n ). However, this string needs to be traversed every time. The code written in this way is as follows. Timeout.
Class Solution {public: vector
Anagrams (vector
& Strs) {vector
Result; int len = strs. size (); bool checked [len]; memset (checked, 0, len * sizeof (bool); for (int I = 0; I
Another way is to determine whether two strings are the same as each other and sort them first. If they are the same after sorting, they are the same. Although the time complexity determined separately is O (nlogn), this information can be reused. This is the case for this question. Therefore, you can use a hash table to record all the modified words.
class Solution {public: vector
anagrams(vector
& strs) { vector
result; map
> codeToStrs; int len = strs.size(); for(int i=0; i
>::iterator it = codeToStrs.begin(); it!=codeToStrs.end(); it++){ if(it->second.size()<2){ continue; } result.insert(result.begin(), it->second.begin(), it->second.end()); } return result; } string getCode(string s){ std::sort(s.begin(), s.end()); return s; }};