Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if two Strings are anagram of each other using basic Java [duplicate]

Tags:

java

anagram

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);
like image 839
Prakhar Londhe Avatar asked Mar 23 '16 14:03

Prakhar Londhe


Video Answer


3 Answers

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);
    } 
like image 185
Ivan Valeriani Avatar answered Oct 08 '22 03:10

Ivan Valeriani


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.

like image 33
Bohemian Avatar answered Oct 08 '22 01:10

Bohemian


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;
}
like image 9
Long Vu Avatar answered Oct 08 '22 02:10

Long Vu