I am writing following code in java Netbeans which is working quite good for normal anagrams. But if the two text fields contain words which contain repetitive letters, then the code fail to work. What may be the problem and how can I solve it? I am quite basic to Java and cannot understand Arrays yet.
String s1= t1.getText();
String s2= t2.getText();
int b=0,c=0;
if(s1.length()!=s2.length())
System.out.print("No");
else {
for(int i=0;i<s1.length();i++) {
char s = s1.charAt(i);
for(int j=0;j<s2.length();j++) {
if(s==s2.charAt(j)){
b++;
}
}
if(b==0)
break;
}
if(b==0)
System.out.print("No");
else
System.out.print("YES");
}
System.out.print(b);
I would go for something simpler to reason about: two strings are anagrams if, once sorted, they match exactly. So in Java it would be something like:
String s1 = "cat";
String s2 = "tac";
boolean isAnagram = false;
if (s1.length() == s2.length()) {
char[] s1AsChar = s1.toCharArray();
char[] s2AsChar = s2.toCharArray();
Arrays.sort(s1AsChar);
Arrays.sort(s2AsChar);
isAnagram = Arrays.equals(s1AsChar, s2AsChar);
}
You want to compare the sorted characters. It's a one-liner:
return Arrays.equals(s1.chars().sorted().toArray(),
s2.chars().sorted().toArray());
Arrays.equals()
compares lengths and all elements for you.
Here my solution, we count the appearance of each character in the first string then subtracting it from the count in the second string. Finally, check if the character count is not 0 then the two string is not anagram.
public static boolean isAnagram(String a, String b){
//assume that we are using ASCII
int[] charCnt = new int[256];
for(int i = 0; i < a.length(); i++){
charCnt[a.charAt(i)]++;
}
for(int i = 0; i< b.length(); i++){
charCnt[b.charAt(i)]--;
}
for(int i = 0; i<charCnt.length; i++){
if(charCnt[i] != 0) return false;
}
return true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With