0

The below code working without error but it not getting proper result for anagram. The if condition is return false for correct value.

import java.util.*;

public class Anagram{
    public boolean solve(String s1, String s2){
        if(s1.length() != s2.length()) return false;
        
        String[] s11 = s1.split("");
        String[] s12 = s2.split("");

        Arrays.sort(s11);
        System.out.println(Arrays.toString(s11));
        Arrays.sort(s12);
        System.out.println(Arrays.toString(s12));

        
        for(int i = 0; i < s1.length(); i++){
            if(s11[i] != s12[i])
             System.out.println(s11[i]);
             System.out.println(s12[i]);
             return false;
        }

        return true;
    }

    public static void main(String[] args){
        String s1 = "restful";
        String s2 = "fluster";

        Anagram v = new Anagram();

        if(v.solve(s1, s2)){
            System.out.println(s2 + " is anagram of the " + s1);
        }else{
            System.out.println("not an anagram");
        }
    }
}

Please let me know why it is not working

1 Answers1

0

Ideally here no need to check individual character from both the Array You can directly check both the Sorted Arrays are equals or not. Replace your for loop with the below code :

if(!Arrays.equals(s11, s12)){
        return false ;
}

Also your code is not working because == is comparing the reference and not the value in Java

drjansari
  • 181
  • 11