8000 2 · kaincode/leetcode@941c2d7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 941c2d7

Browse files
committed
2
1 parent f11d2e8 commit 941c2d7

File tree

1 file changed

+16
-20
lines changed

1 file changed

+16
-20
lines changed

Anagrams/Anagrams.cpp

Lines changed: 16 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,21 @@
11
class Solution {
22
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;
96
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+
}
1318
}
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;
2420
}
25-
};
21+
};

0 commit comments

Comments
 (0)
0