Java Anagrams

  • + 0 comments
    import java.util.Scanner;
    
    public class Solution {
    
        static boolean isAnagram(String a, String b) {
            if(a.length() != b.length()){
                return false;
            }
            String A = a.toLowerCase();
            String B = b.toLowerCase();
            java.util.Set<String> charSet = new java.util.HashSet<>();
            for(char a1: A.toCharArray()){
                if(!charSet.contains(String.valueOf(a1))){
                    charSet.add(String.valueOf(a1));
                    int counter1 = 0;
                    int counter2 = 0;
                    for(char a2: A.toCharArray()){
                        if(a1 == a2){
                            counter1++;
                        }
                    }
                    for(char b1: B.toCharArray()){
                        if(a1 == b1){
                            counter2++;
                        }
                    }
                    if(counter1 != counter2){
                        return false;
                    }
                }
            }
                
            return true;
        }
    
      public static void main(String[] args) {
        
            Scanner scan = new Scanner(System.in);
            String a = scan.next();
            String b = scan.next();
            scan.close();
            boolean ret = isAnagram(a, b);
            System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
        }
    }