Use a hash table to record it. The tricky part is that when the hash value is > 0, it is the index + 1. Otherwise, that string already exists in result list.
1 class Solution { 2 public: 3 vectoranagrams(vector &strs) { 4 vector result; 5 int len = strs.size(); 6 if (len < 2) return result; 7 unordered_map mapping; 8 for (int i = 0; i < len; i++) { 9 string tmp = strs[i];10 sort(tmp.begin(), tmp.end());11 if (mapping[tmp]) {12 if (mapping[tmp] > 0) {13 result.push_back(strs[mapping[tmp]-1]);14 mapping[tmp] = -1;15 }16 result.push_back(strs[i]);17 } else {18 mapping[tmp] = i+1;19 }20 }21 return result;22 }23 };