forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
anagram_program.c
65 lines (61 loc) · 1.34 KB
/
anagram_program.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
55
56
57
58
59
60
61
62
63
64
65
//C program to check if two input strings are anagrams or not
#include <stdio.h>
#include <string.h>
void sort_strings(char str[]) //sort the strings
{
int loop1, loop2;
char temp;
for (loop1 = 0; str[loop1] != '\0'; loop1++)
{
for (loop2 = 0; str[loop2] != '\0'; loop2++)
{
if (str[loop2] > str[loop1])
{
temp = str[loop1]; //swapping
str[loop1] = str[loop2];
str[loop2] = temp;
}
}
}
}
int check_anagram(char str1[], char str2[], int len)
{
int loop_num;
for (loop_num = 0; loop_num < len; loop_num++)
{
if (str1[loop_num] != str2[loop_num])
return -1;
}
return 0;
}
int main()
{
char str1[50], str2[50];
int len1, len2;
printf("Enter two strings:\n");
scanf("%s%s", str1, str2); //strings to be checked
len1 = strlen(str1);
len2 = strlen(str2);
//if length of strings is not equal they cannot be anagrams
if (len1 != len2)
printf("The given strings are not anagrams");
else
{
sort_strings(str1);
sort_strings(str2);
if (check_anagram(str1, str2, len1) == 0) //len1=len2
printf("The given strings are anagrams");
else
printf("The given strings are not anagrams");
}
return 0;
}
/*
TIME COMPLEXITY-O(nlogn)
SPACE COMPLEXITY-O(n)
SAMPLE INPUT
restful
fluster
OUTPUT
The given strings are anagrams
*/