Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 52 additions & 21 deletions c++/anagrams.cpp
Original file line number Diff line number Diff line change
@@ -1,29 +1,60 @@
#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <cctype>

using namespace std;

class Solution {
public:
vector<string> anagrams(vector<string> &strs) {
/* https://oj.leetcode.com/problems/anagrams/
["abc", "ef", "cba", "xy", "yx"] -> ["abc", "cba", "xy", "yx"]
the order doesn't matter
*/

vector<string> anagrams(vector<string>& strs) {
if (strs.empty() || strs.size() == 1) {
return {};
}

unordered_map<string, vector<string>> dict;

for (const string& str : strs) {
string sorted_str = sortString(str);
dict[sorted_str].push_back(str);
}

vector<string> result;
unordered_map<string, string> dict;

for (int i = 0; i < strs.size(); i++) {
string s = strs[i];
sort(s.begin(), s.end());
if (dict.find(s) == dict.end()) {
dict[s] = strs[i];
}
else {
if (dict[s] != "#") {
result.push_back(dict[s]);
dict[s] = "#";
for (const auto& pair : dict) {
if (pair.second.size() > 1) {
for (const string& s : pair.second) {
result.push_back(s);
}
result.push_back(strs[i]);
}
}

return result;
}
};

private:
string sortString(const string& str) {
string sorted_str;
for (char c : str) {
if (!isspace(c) && !ispunct(c)) {
sorted_str += tolower(c);
}
}
sort(sorted_str.begin(), sorted_str.end());
return sorted_str;
}
};

int main() {
Solution sol;
vector<string> strs = {"Listen", "Silent", "The eyes", "They see", "abc", "cba", "xy", "yx", "ef"};
vector<string> result = sol.anagrams(strs);

cout << "Anagrams in the list are: ";
for (const string& s : result) {
cout << s << " ";
}
cout << endl;

return 0;
}