Java Anagrams

  • + 1 comment

    Very Simple way in Java 15: firstly we converted our Strings into lowerCase letters then we are checking the length of the strings if they are not equal then they are not Anagrams so the program will exit from there. if there lengths are equal then we are going to use Arrays.sort() (built-in method) to sort the letters, and then we are comparing both the strings with their index values , if all the Letters are equal then it is Anagram.

    import java.io.; import java.util.;

    public class Solution {

    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        String a = sc.next();
        String b = sc.next();
        String A = a.toLowerCase();
        String B = b.toLowerCase();
        char c1[] = A.toCharArray();
        char c2[] = B.toCharArray();
        if(c1.length != c2.length){
            System.out.println("Not Anagrams");
            System.exit(0);
        }
        Arrays.sort(c1);
        Arrays.sort(c2);
        for(int i =0; i<c1.length;i++){
            if(c1[i] != c2[i]){
                System.out.println("Not Anagrams");
                System.exit(0);
            }
        }
        System.out.println("Anagrams");
    }
    
    }