forked from ianshulx/DSA-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagram.cpp
78 lines (67 loc) · 1.46 KB
/
Anagram.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool IsAnagram(
string str1,
string str2)
{
// Anagram is not case sensitive
// so we convert all characters
// to uppercase
transform(
str1.begin(),
str1.end(),
str1.begin(),
::toupper);
transform(
str2.begin(),
str2.end(),
str2.begin(),
::toupper);
// Anagram does not care about space
// so we remove all spaces if any
str1.erase(
remove(
str1.begin(),
str1.end(),
' '),
str1.end());
str2.erase(
remove(
str2.begin(),
str2.end(),
' '),
str2.end());
// Then, we sort string1 and string2
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
// If they both are anagram,
// they will be exactly same after sorted
return str1 == str2;
}
int main()
{
cout << "Anagram" << endl;
// Input string1
string string1;
cout << "Input string 1 -> ";
getline(cin, string1);
// Input string2
string string2;
cout << "Input string 2 -> ";
getline(cin, string2);
// Check if they are anagram
cout << "'" << string1 << "' and '";
cout << string2 << "' are ";
if(IsAnagram(string1, string2))
{
cout << "anagram";
}
else
{
cout << "NOT anagram";
}
cout << endl;
return 0;
}