forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnagram.java
66 lines (55 loc) · 1.45 KB
/
Anagram.java
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
/*
Anagrams are strings formed by rearranging the
letters of another string.
Example: LISTEN and SILENT, as they have the same
characters just appearing in another order.
*/
import java.util.Scanner;
class Anagram
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1st string");
String str1 = sc.nextLine();
System.out.println("Enter 2nd string");
String str2 = sc.nextLine();
int count1[] = new int[256];
int count2[] = new int[256];
// if lengths are not equal, they cannot be anagrams
if (str1.length() != str2.length())
{
System.out.println("The strings are not anagrams");
return;
}
// Store the count of every character in string
for (int i = 0; i < str1.length(); i++)
{
count1[str1.charAt(i) - 'a']++;
count2[str2.charAt(i) - 'a']++;
}
// If the counts of characters are not equal,
// they are not anagrams
for (int i = 0; i < 256; i++)
{
if (count1[i] != count2[i])
{
System.out.println("The strings are not anagrams");
return;
}
}
System.out.println("The strings are anagrams");
}
}
/*
Input:
car
arc
Output:
The strings are anagrams
Input:
cap
tap
Output:
The strings are not anagrams
*/