-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanagrams.java
More file actions
34 lines (34 loc) · 1.29 KB
/
anagrams.java
File metadata and controls
34 lines (34 loc) · 1.29 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
import java.util.Arrays;
public class anagrams
{
public static void main(String[]args)
{
String str1="earth";
String str2="heart";
//Convert Strings to lowercase. Why? so thatwe don't have to checkseparately for lower & uppercase.
str1=str1.toLowerCase();
str2=str2.toLowerCase();// First check - if the lengths are the same
if(str1.length() ==str2.length())
{
// convert strings into char array
char[]str1charArray=str1.toCharArray();
char[]str2charArray=str2.toCharArray();
// sort the char array
Arrays.sort(str1charArray);
Arrays.sort(str2charArray);
// if the sorted char arrays are sameor identical then the strings areanagram
boolean result=Arrays.equals(str1charArray,str2charArray);
if(result) {
System.out.println(str1+" and "+str2+" are anagrams of eachother.");
}
else
{
System.out.println(str1+" and "+str2+" are not anagrams ofeach other.");
}
}else
{
// case when lengths are not equal
System.out.println(str1+" and "+str2+" are not anagrams of eachother.");
}
}
}