Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Analysis:
Anagrams is two strings are using the same characters.
One way to compare two strings is use sort(). e.g.
sort(str1.begin(), str1.end());
sort(str1.begin(), str1.end());
if (str1.compare(str2)==0) // when two strings are equal, the func returns 0
A more efficient way:
1. Scan the whole string vector, for each string, store to a hash map with the "ordered string" as the key. O(n).
2. Scan the whole hash map, output the values where for one key the number of value >=2. O(n)
Note:
1. We can use multimap<string, string> in c++, which allows the duplicate key values.
2. To store key-value into multimap, use ".insert(pair<key_type, value_type>(key,value))"
3. Use "pair<multimap<string,string>::iterator,multimap<string,string>::iterator> ret;" and
".equal_range()" which returns a iterator pair(ret) that the "first" is the lower bound and "second" is the upper bound, to get all the key-values pairs for one key.
4. To check the number of values in one key, use the .count(key) method.
Java
public List<String> anagrams(String[] strs) {
List<String> result = new ArrayList<>();
HashMap<String, Integer> anagramMap = new HashMap<String,Integer>();
for(int i=0;i<strs.length;i++){
String t1 = strs[i];
char [] s1= t1.toCharArray();
Arrays.sort(s1);
t1 = new String(s1);
if(!anagramMap.containsKey(t1)){
anagramMap.put(t1, i);
}else {
result.add(strs[i]);
if(anagramMap.get(t1)!=-1){
result.add(strs[anagramMap.get(t1)]);
anagramMap.put(t1, -1);
}
}
}
return result;
}
c++
vector<string> anagrams(vector<string> &strs) {
vector<string> result;
map<string,int> temp;
for(int i=0; i<strs.size();i++){
string str = strs[i];
sort(str.begin(),str.end());
if(temp.find(str) == temp.end()){
temp[str] = 1;
}
else{
temp[str]++;
}
}
for(int i=0; i<strs.size();i++){
string str = strs[i];
sort(str.begin(),str.end());
if(temp.find(str) != temp.end() && temp[str]>1){
result.push_back(strs[i]);
}
}
return result;
}