-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1_4.cpp
56 lines (46 loc) · 1.24 KB
/
1_4.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
/* Write a method to decide if two strings are anagrams or not. */
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool isAnagrams1(string str1, string str2)
{
if(str1.length() != str2.length() || str1 == "" || str2 == "")
return false;
sort(&str1[0], (&str1[0] + str1.length()));
sort(&str2[0], (&str2[0] + str2.length()));
if(str1 == str2)
return true;
else
return false;
}
bool isAnagrams2(string str1, string str2)
{
if(str1.length() != str2.length() || str1 == "" || str2 == "")
return false;
int arr[256]; // There 2^8 characters in ASCII table
memset(arr, 0, sizeof(arr));
int len = str1.length();
for(int i = 0; i < len; i++)
{
arr[(int) str1[i]]++;
arr[(int) str2[i]]--;
}
for(int j = 0; j < len; j++)
{
if(0 != arr[j])
return false;
}
return true;
}
int main()
{
string str1 = "abcdefg";
string str2 = "edcbafg";
bool result1 = isAnagrams1(str1, str2);
bool result2 = isAnagrams2(str1, str2);
cout << "String 1: " << str1 << " and String 2: " << str2 << " is anagrams is " << result1 << endl;
cout << "String 1: " << str1 << " and String 2: " << str2 << " is anagrams is " << result2 << endl;
// system("pause");
return 0;
}