Favorite question of interviewer.
package com.iacsd.java;
import java.util.Arrays;
import java.util.Scanner;
public class anagram
{
public static void main(String[] args)
{
Scanner sc =new Scanner(System.in);
String s1=sc.nextLine(); // enter the first string
String s2=sc.nextLine(); // enter the second string
if(s1.length() == s2.length()) // compare the length of both string
{
char arr1[]=s1.toCharArray(); // convert the string into a character type array
char arr2[]=s2.toCharArray(); // convert the string into a character type array
Arrays.sort(arr1); // By calling sort method, we sort the array
Arrays.sort(arr2);
boolean check=true; // variable for checking
for(int i=0; i<arr1.length; i++)
{
if(arr1[i]!=arr2[i]) // compare the character of both character type array
{
check=false;
}
}
if(check==true)
{
System.out.println("Both strings are anagram");
}
else
{
System.out.println("not anagram");
}
}
}
}
example-
i/p 1 is army
i/p 2 is mary
o/p strings are anagram.
i/p 1 abc
i/p 2 zxc
o/p strings are not anagram.
No comments:
Post a Comment