Write a java program to check Anagram.

Write a program to check whether the two given strings are anagrams.

Note: Rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once is called Anagram.”

returns an int. The method returns 1 if the 2 strings are anagrams. Else it returns -1.

Input and Output Format:

Input consists of 2 strings. Assume that all characters in the string are lower case letters.

The output consists of a string that is either “Anagrams” or “Not Anagrams”.

Sample Input 1:

eleven plus two

twelve plus one

Sample Output 1:

Anagrams

Sample Input 2:

orchestra

carthorse

Sample Output 2:

Anagrams

Sample Input 3:

assdfggg

technologies

Sample Output 3:

Not Anagrams

Check Anagram in Java.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    String s1 = sc.nextLine();
    String s2 = sc.nextLine();
    List<Character> l1 = new ArrayList<Character>();
    List<Character> l2 = new ArrayList<Character>();
    String s3 = s1.replace(" ", "");
    String s4 = s2.replace(" ", "");
    String s5 = s3.toUpperCase();
    String s6 = s4.toUpperCase();
    for (int i = 0; i < s5.length(); i++) {
      l1.add(s5.charAt(i));
    }
    for (int i = 0; i < s6.length(); i++) {
      l2.add(s6.charAt(i));
    }

    Collections.sort(l1);
    Collections.sort(l2);
    
    if (l1.equals(l2))
      System.out.println("true");
    else
      System.out.println("false");

  }
}

 

Add a Comment

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

eighteen + eight =