-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagram.java
More file actions
62 lines (53 loc) · 1.86 KB
/
Anagram.java
File metadata and controls
62 lines (53 loc) · 1.86 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
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
/*
A word, phrase, or sentence formed from another by rearranging
its letters is knoen as anagrams. Thus the anagram of ten is net.
Write a method that check if a given two words are anagram or not
*/
package com.fsmvu.programmingproblemsolving;
import java.util.Arrays;
public class Anagram {
public static boolean isAnagram(String w1, String w2){
// check if they both have the same length
if(w1.length()!=w2.length())
return false;
//create an array that represents all leters
int[] balance= new int[26];
// count the occurance number of each letter, if the occurance on both sides if equal,the result will be zero
for(int i=0; i<w1.length();i++){
balance[w1.charAt(i)-'a']++;
balance[w2.charAt(i)-'a']--;
}
//check if the balance is achieved
for(int i=0; i<balance.length; i++){
if(balance[0]!=0)
return false;
}
return true;
}
/* second approach to the problem:
create a char array for each word and sort them
if sorted arrays are equal then they are anagram*/
public static boolean isAnagram2(String w1, String w2){
if(w1.length()!=w2.length()){
return false;
}
char[] w1char=new char[w1.length()];
char[] w2char=new char[w2.length()];
//assign the string characters to char array
for(int i=0; i<w1.length();i++){
w1char[i]=w1.charAt(i);
}
for(int i=0; i<w2.length();i++){
w2char[i]=w2.charAt(i);
}
Arrays.sort(w2char);
Arrays.sort(w1char);
//check the to array are equal after sorting
for(int i=0; i<w1char.length;i++){
if(w1char[i]!=w2char[i]){
return false;
}
}
return true;
}
}