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
84 changes: 55 additions & 29 deletions c++/anagrams.cpp
Original file line number Diff line number Diff line change
@@ -1,29 +1,55 @@
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> 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] = "#";
}
result.push_back(strs[i]);
}
}

return result;
}
};
#include<iostream>
#include<string>
using namespace std;
int main()
{
string first = "";
string second = "";
cout << "\nEnter the First Word: ";
getline(cin, first);
cout << "\nEnter the Second Word: ";
getline(cin, second);
int letters_counter=0;
if (first.length() == second.length())
{
bool found = false;

for (int i = 0; i < first.length(); i++)
{
for (int j = 0; j < second.length(); j++)
{
if (first[i] == second[j])
{
found = true;
break;
}

}

if (found)
{
letters_counter += 1;
}
}
if (letters_counter == first.length())
{
cout << "\nANAGRAMS";
}
else
{
cout << "\nNOT ANAGRAMS";
}

}
else
{
cout << "\nNOT ANAGRAMS";
cout << endl << endl;
system("pause");
return 0;
}

cout << endl << endl;
system("pause");
return 0;
}