forked from AkashMarkad/Hacktoberfest-2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Anagram.java
37 lines (30 loc) · 1.09 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
import java.util.Arrays;
/**
* Description: Two strings are said to be anagram if we can form one string by arranging the characters of another string.
*/
public class Anagram {
public static void main(String[] args) {
Anagram.isAnagram( "Race", "Care"); // This is Anagram
Anagram.isAnagram( "Wars", "Raw"); // This is NOT Anagram
Anagram.isAnagram( "King", "Ring"); // This is NOT Anagram
}
private static void isAnagram(String str1, String str2) {
str1 = str1.toLowerCase();
str2 = str2.toLowerCase();
// convert strings to char array
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// sort the char array
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// check if sorted char arrays are same
boolean result = Arrays.equals(charArray1, charArray2);
// If sorted array are the same and have same length then the string is anagram
if(result && (str1.length() == str2.length())) {
System.out.println(str1 + " & " + str2 + " are Anagram.");
}
else {
System.out.println(str1 + " & " + str2 + " are NOT Anagram.");
}
}
}