forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagrams.cpp
54 lines (47 loc) · 1.37 KB
/
Anagrams.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: June 22, 2012
Problem: Anagrams
Difficulty: easy
Source: http://www.leetcode.com/onlinejudge
Notes:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Solution:
sort every string in alphabetical order and create a mapping from the original
string to the sorted string. Then traverse the sorted string array to get the
mapping orignal result strings.
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <cstring>
#include <map>
using namespace std;
class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
vector<string> result;
map<string, vector<string> > dict;
if (strs.size() == 0) {
return result;
}
for (size_t i = 0; i < strs.size(); i++) {
string sorted(strs[i]);
sort(sorted.begin(), sorted.end());
dict[sorted].push_back(strs[i]);
}
map<string, vector<string> >::iterator it;
for (it = dict.begin(); it != dict.end(); it++) {
if (it->second.size() > 1) {
for (size_t i = 0; i < it->second.size(); i++) {
result.push_back(it->second[i]);
}
}
}
return result;
}
};