-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakingAnagrams.cpp
More file actions
65 lines (51 loc) · 1.36 KB
/
MakingAnagrams.cpp
File metadata and controls
65 lines (51 loc) · 1.36 KB
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
/*
Determine the min number of steps to
convert two given string of lower-case
English characters into anagrams of
each other. Two strings are anagrams if
they have the same letters with the same
frequencies but in a different order.
i.e., acde and edca are anagrams.
Input: two string of different lengths
Output: an integer denoting the number of
necessary deletions.
*/
#include <iostream>
using namespace std;
// Complete the makeAnagram function below.
int makeAnagram(string a, string b) {
// Define an array of size 26 for lowercase English letters
int arr[26] = {0};
// Intialise the counter
int num_del = 0;
// Add frequencies of a to the array
for(int i = 0; i < a.length(); i++)
{
arr[a[i] - 'a']++;
}
// Subtract frequencies of b to the array
for(int i = 0; i < b.length(); i++)
{
arr[b[i] - 'a']--;
}
// The difference is the number of characters
// needed to be deleted.
for(int i = 0; i < 26; i++)
{
//cout << arr[i] << " ";
if(arr[i] != 0)// && arr[i] % 2 != 0)
//since numbers in the array could be -ve, absolute values are taken
num_del += abs(arr[i]);
}
return num_del;
}
int main()
{
string a;
getline(cin, a);
string b;
getline(cin, b);
int res = makeAnagram(a, b);
cout << res << endl;
return 0;
}