File tree Expand file tree Collapse file tree 1 file changed +16
-20
lines changed Expand file tree Collapse file tree 1 file changed +16
-20
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public:
3
- vector<string> anagrams (vector<string>& strs) {
4
- // Start typing your C/C++ solution below
5
- // DO NOT write int main() function
6
-
7
- map<string, vector<int >> dict;
8
-
3
+ vector<string> anagrams (vector<string> &strs) {
4
+ vector<string> result;
5
+ map<string, int > exists;
9
6
for (int i = 0 ; i < strs.size (); i++) {
10
- string copy_string (strs[i]);
11
- sort (copy_string.begin (), copy_string.end ());
12
- dict[copy_string].push_back (i);
7
+ string u = strs[i];
8
+ sort (u.begin (), u.end ());
9
+ if (exists.find (u) == exists.end ()) {
10
+ exists[u] = i;
11
+ } else {
12
+ if (exists[u] >= 0 ) {
13
+ result.push_back (strs[exists[u]]);
14
+ exists[u] = -1 ;
15
+ }
16
+ result.push_back (strs[i]);
17
+ }
13
18
}
14
-
15
- vector<string> anagrams;
16
- for (auto iter = dict.begin (); iter != dict.end (); iter++) {
17
- vector<int >& string_id = iter->second ;
18
- if (string_id.size () <= 1 ) continue ;
19
- for (int i = 0 ; i < string_id.size (); i++)
20
- anagrams.push_back (strs[string_id[i]]);
21
- }
22
-
23
- return move (anagrams);
19
+ return result;
24
20
}
25
- };
21
+ };
You can’t perform that action at this time.
0 commit comments