Check Anagram Words

Write a program to check whether two string are anagram or not?

Meanng of Anagram : –

If all the letters of two words are matching, it is called Anagrams

Example – SIMPLE and LEPSIM are Anagram

import java.util.HashMap;
import java.util.Map;

public class MyClass {
    public static void main(String args[]) {
      String str = "carrace";
        String str1 = "racecar";
        Map<Character,Integer>mp = new HashMap<>();
        Map<Character,Integer>mp1 = new HashMap<>();
        for(int i=0;i<str.length();i++){
            char ch = str.charAt(i);
            if(mp.get(ch)==null){
                mp.put(ch, 1);
            }
            else{
                mp.put(ch,mp.get(ch)+1);
            }
        }
        for(int i=0;i<str1.length();i++){
            char ch = str1.charAt(i);
            if(mp1.get(ch)==null){
                mp1.put(ch, 1);
            }
            else{
                mp1.put(ch,mp1.get(ch)+1);
            }
        }
        if(mp.equals(mp1)){
            System.out.println("Anagram");
        }
        else{
            System.out.println("Not Anagram");
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *