-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathquestion9.c
54 lines (48 loc) · 1.19 KB
/
question9.c
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
/*
Check whether given two strings are anagrams of each other
Two strings are anagrams if they have same no of characters and they are composed of the same letters.
Even if there are repetitions, they are going to be same.
METHOD1:
sort and scan
Time complexity: O(nlogn)
Space complexity: O(1) //for inplace sorting
METHOD2:
use hash table and increment count for first string and decrement for second. In the end all count
values should be zero.
Time complexity: O(n)
Space complexity: O(1) //256 not dependent on input
*/
//sorting method not done as it is very basic
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define size 256
void checkAnagram(char *str1, char *str2, int l1, int l2){
int hash[size] = {0};
int i;
for(i=0;i<l1;i++){
hash[str1[i]]++;
}
for(i=0;i<l2;i++){
hash[str2[i]]--;
}
for(i=0;i<size;i++){
if(hash[i] > 0){
printf("two strings are NOT anagrams\n");
return;
}
}
printf("two strings are anagrams of each other\n");
}
int main(){
char str1[] = "heater";
char str2[] = "reheaa";
int l1 = strlen(str1);
int l2 = strlen(str2);
if(l1 != l2){
printf("two strings not NOT anagrams\n");
return 0;
}
checkAnagram(str1,str2, l1, l2);
return 0;
}