Tuesday, September 19, 2023

How to check if two String are Anagram in Java - Program Example

Write a Java program to check if two String is an anagram of each other, is another good coding question asked at fresher level Java Interviews. This question is on a similar level of finding the middle element of LinkedList in one pass and swapping two numbers without using the temp variable. By the way, two String is called anagram, if they contain the same characters but on different order e.g. army and mary, stop and pots, etc. Anagrams are actually a mix-up of characters in String. If you are familiar with String API, i.e. java.lang.String then you can easily solve this problem.

In order to check if  Strings are anagrams, you need to get their character array and see if they are equal or not. Though you can also use indexOf(), substring(), and StringBuffer or StringBuilder class to solve this question. 

In this Java program, we will see 3 ways to solve these interview questions, and check if two String are anagrams or not. By the way, if you are preparing for a Java interview, it's good to prepare some data structures and algorithms questions as well. More often, there is one or more questions from programming, coding, and logic in these interviews.



Java program to check if String is an anagram

String Anagram Check - 3 ways to find if two Strings are anagrams or notAs I said, there are multiple ways to find if two strings are anagrams or not. The classical way is getting a character array of each String, and then comparing them, if both char array is equal then Strings are anagram. 

But before comparing, make sure that both Strings are in the same case e.g. lowercase or uppercase and character arrays are sorted because equals method of Arrays, return true, only if the array contains the same length, and each index has the same character. 



For simplicity, I have left checking if String is null or empty and converting them into uppercase or lowercase, you can do that if you want. If the Interviewer asks you to write production quality code, then I would suggest definitely put those checks and throw IllegalArgumentException for null String or you can simply return false.

I would personally prefer to return false rather than throwing Exception, similar to the equals() method. Anyway, here are three ways to check if two String are Anagram or not. I have also included a JUnit Test to verify various String which contains both anagram and not.

import java.util.Arrays;

/**
 * Java program - String Anagram Example.
 * This program checks if two Strings are anagrams or not
 *
 * @author Javin Paul
 */
public class AnagramCheck {
   
    /*
     * One way to find if two Strings are anagram in Java. This method
     * assumes both arguments are not null and in lowercase.
     *
     * @return true, if both String are anagram
     */
    public static boolean isAnagram(String word, String anagram){       
        if(word.length() != anagram.length()){
            return false;
        }
       
        char[] chars = word.toCharArray();
       
        for(char c : chars){
            int index = anagram.indexOf(c);
            if(index != -1){
                anagram = anagram.substring(0,index) 
                       + anagram.substring(index +1, anagram.length());
            }else{
                return false;
            }           
        }
       
        return anagram.isEmpty();
    }
   
    /*
     * Another way to check if two Strings are anagram or not in Java
     * This method assumes that both word and anagram are not null and lowercase
     * @return true, if both Strings are anagram.
     */
    public static boolean iAnagram(String word, String anagram){
        char[] charFromWord = word.toCharArray();
        char[] charFromAnagram = anagram.toCharArray();       
        Arrays.sort(charFromWord);
        Arrays.sort(charFromAnagram);
       
        return Arrays.equals(charFromWord, charFromAnagram);
    }
   
   
    public static boolean checkAnagram(String first, String second){
        char[] characters = first.toCharArray();
        StringBuilder sbSecond = new StringBuilder(second);
       
        for(char ch : characters){
            int index = sbSecond.indexOf("" + ch);
            if(index != -1){
                sbSecond.deleteCharAt(index);
            }else{
                return false;
            }
        }
       
        return sbSecond.length()==0 ? true : false;
    }
}

JUnit Test Case for String Anagram Example

here is our JUnit tests for all three 3 methods of AnagramCheck class, we have actually tested all method with similar set of input.
import org.junit.Test;
import static org.junit.Assert.*;

/**
 * JUnit test class to test various anagram program for various String input.
 */
public class StringAnagramTest {
   
 
    @Test
    public void testIsAnagram() {
        assertTrue(AnagramCheck.isAnagram("word", "wrdo"));
        assertTrue(AnagramCheck.isAnagram("mary", "army"));
        assertTrue(AnagramCheck.isAnagram("stop", "tops"));
        assertTrue(AnagramCheck.isAnagram("boat", "btoa"));
        assertFalse(AnagramCheck.isAnagram("pure", "in"));
        assertFalse(AnagramCheck.isAnagram("fill", "fil"));
        assertFalse(AnagramCheck.isAnagram("b", "bbb"));
        assertFalse(AnagramCheck.isAnagram("ccc", "ccccccc"));
        assertTrue(AnagramCheck.isAnagram("a", "a"));
        assertFalse(AnagramCheck.isAnagram("sleep", "slep"));
       
    }
   
    @Test
    public void testIAnagram() {
        assertTrue(AnagramCheck.iAnagram("word", "wrdo"));
        assertTrue(AnagramCheck.iAnagram("boat", "btoa"));
        assertFalse(AnagramCheck.iAnagram("pure", "in"));
        assertFalse(AnagramCheck.iAnagram("fill", "fil"));
        assertTrue(AnagramCheck.iAnagram("a", "a"));
        assertFalse(AnagramCheck.iAnagram("b", "bbb"));
        assertFalse(AnagramCheck.iAnagram("ccc", "ccccccc"));
        assertFalse(AnagramCheck.iAnagram("sleep", "slep"));
       
    }
    
    @Test
    public void testcheckAnagram() {
        assertTrue(AnagramCheck.checkAnagram("word", "wrdo"));       
        assertFalse(AnagramCheck.checkAnagram("b", "bbb"));
        assertFalse(AnagramCheck.checkAnagram("ccc", "ccccccc"));
        assertTrue(AnagramCheck.checkAnagram("a", "a"));
        assertFalse(AnagramCheck.checkAnagram("sleep", "slep"));
        assertTrue(AnagramCheck.checkAnagram("boat", "btoa"));
        assertFalse(AnagramCheck.checkAnagram("pure", "in"));
        assertFalse(AnagramCheck.checkAnagram("fill", "fil"));
       
    }
}

Output
Testsuite: StringAnagramTest
Tests run: 3, Failures: 0, Errors: 0, Time elapsed: 0.094 sec

Our AnagramCheck class contains 3 static methods to verify if Strings are anagram or not. First one, takes character array of first String and loop through it, then finds that character in second String, and deletes it by using substring method. If second String doesn't contains a character than the method return false immediately. 

At the end of the test if the second String is empty than both Strings are anagram because they contain the same set of characters. To improve performance, we have checked length at the very start of this method, as two String with different lengths can not be anagram of each other. 

The third method is exactly same of first one, except, it uses deleteCharAt(int index) method of StringBuilder for deleting characters.


That's all on how to check if two String are anagrams of each other. Don't forget to check other popular programming and coding questions from various Java interviews, mentioned below :

And lastly one question for you, which coding exercise if your favorite in Java? Fibonacci, Palindrome, Permutation, Prime number or this one?

61 comments :

SARAL SAXENA said...

Hi Javin...few things that I want to add...Two words are anagrams of each other if they contain the same number of characters and the same characters. You should only need to sort the characters in lexicographic order, and compare if String a is equal to String b at all steps.

Here's a code example. Look into Arrays in the API to understand what's going on here.

public boolean isAnagram(String firstWord, String secondWord) {
char[] word1 = firstWord.replaceAll("[\\s]", "").toCharArray();
char[] word2 = secondWord.replaceAll("[\\s]", "").toCharArray();
Arrays.sort(word1);
Arrays.sort(word2);
return Arrays.equals(word1, word2);
}

Unknown said...

return sbSecond.length()==0 ? true : false

I think that the conditional operator is unnecessary. :)

Govind Sharma said...

Here is a simple code

import java.util.*;

class Anagram
{
public static void main(String args[]) throws Exception
{
Boolean FLAG=true;

Scanner sc= new Scanner(System.in);

System.out.println("Enter 1st string");

String s1=sc.nextLine();

System.out.println("Enter 2nd string");

String s2=sc.nextLine();

int i,j;
i=s1.length();
j=s2.length();

if(i==j)
{
for(int k=0;k<i;k++)
{
for(int l=0;l<i;l++)
{
if(s1.charAt(k)==s2.charAt(l))
{
FLAG=true;
break;
}
else
FLAG=false;
}
}
}
else
FLAG=false;
if(FLAG)
System.out.println("Given Strings are anagrams");
else
System.out.println("Given Strings are not anagrams");
}
}

Lal said...

Compare the length of the two strings. Return false if they are not same.
Take an empty integer array of size 256 to hold the frequency of occurrence of characters in the string.
Iterate through the first string and increment the frequency of each character in its corresponding location in the integer array.
In the same time, iterate through the second string and decrement the frequency of the character in its corresponding location in the integer array.
Iterate through the integer array to check whether it has the value 0. If not, return false. Otherwise, return true.

For explanation and code http://www.algoqueue.com/algoqueue/default/view/7077888/check-whether-two-strings-are-anagram

Anonymous said...

Guys do we require to implement such a complex logic for this. I was thinking what if we add the ascii value of all the characters in the 2 stings. If they are same then its an anagram and if not then its not an anagram. What you say?

Anonymous said...

What is the complexity of this solution? i am looking for a method to decide whether two Strings are anagaram or not in linear time O(n), can I use this one?

Anonymous said...

@Anonymous, two strings are anagram if they contain if they contain same characters. If converting characters to their ASCII value and adding them, you may get a situation where two differnet letters sum to the same number e.g. 4 + 2 = 6 or 3 +3 = 6, both String has differnet character but there sum is same, so I don't see that logic working. What is shown in the solution is correct.

Victor Rodriguez said...

I don't think any of these solutions ignore punctuation and whitespace.

public static boolean areAnagrams(String one, String two) {
String oneLower = one.toLowerCase();
String twoLower = two.toLowerCase();

int sumOne = 0;
for (int x = 0; x < oneLower.length(); x++) {
Character c = oneLower.charAt(x);
if (Character.isLetterOrDigit(c)) {
sumOne += c.charValue();
}
}

int sumTwo = 0;
for (int x = 0; x < twoLower.length(); x++) {
Character c = twoLower.charAt(x);
if (Character.isLetterOrDigit(c)) {
sumTwo += c.charValue();
}
}

return sumOne == sumTwo;
}

Anonymous said...

Complexity seems to be pow(n,2) i.e. {n square} right? Considering substring computation takes O(n) and we are doing for each of n characters in the string(Assuming both strings of length n)...Is it not a fair idea to use HashMaps and compute the same in O(n) at the cost of memory? You would need 256 entries at max? Any thoughts?

Unknown said...

import java.util.*;
import java.lang.String;
public class anagram
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str1=new String();
String str2=new String();
System.out.println("Enter any small string");
str1=sc.next();
System.out.println("Enter other small string");
str2=sc.next();
char arr1[]=str1.toCharArray();
char arr2[]=str2.toCharArray();
int l1=str1.length();
int l2=str2.length();
if(l1==l2)
{
for(int i=0;i<l2;i++)
{
for(int j=0;j<l2;j++)
{
if(arr1[i]==arr2[j]);
{
l1++;
break;
}
}
if(l1!=l2+i+1)
{
System.out.println("Not Anagram");
break;
}
}
if(l1==2*l2)
System.out.println("We got Anagram");
}
else
System.out.print("Not equal length");

}
}

javin paul said...

@devash, would be great if you could list out some key details about your solution e.g. time and space complexity, how it is better than original solution? what improvements you have done etc. If you are just attempting to solve this problem in your style, then also those detail will help other's to check your solution.

Anonymous said...

public static void findAnagram(String word){

StringBuffer bword= new StringBuffer(word);
String anagram=bword.reverse().toString();
if(word.equals(anagram){
System.out.println("anagram");

}else
System.out.println("not");
}

public static void main(String[] args) {

findAnagram("madam");
findAnagram("must");
}

Anonymous said...

What is the simplest way to check if two String are pemutations of each other? You cannot use Hashtable, or any other data structure, solve the problem with plain logic and primitive programming construct.

Unknown said...

One simple way to solve the problem can be:-

public static void main(String args[]) {
String first = "army";
String second = "Mary";
boolean result = isAnagram(first.toLowerCase().trim() , second.toLowerCase().trim());
System.out.println("Is Anagram = "+result);
}

public static boolean isAnagram(String first, String second) {

if(first.length() != second.length())
return false;

HashSet hs = new HashSet();
for(char ch : first.toCharArray()) {
hs.add(ch);
}
for(char ch : second.toCharArray()) {
/* if char is allowed in hashset then it means two strings do not contains same chars */
if(hs.add(ch))
return false;
}
return true;
}

Anonymous said...

The best way of solving it through collections ...great work Nitin

Anonymous said...

More Easier Code than the above all the code
here it is

class Sorted
{
public static void main(String ar[])
{
String a="maonj";
String c="jonam";
char d[]=c.toCharArray();
char b[]=a.toCharArray();
if(b.length!=d.length)
{
System.out.println("It's not Anagram");
System.exit(0);}
for(int i=0;ib[j])
{
char temp=b[i];
b[i]=b[j];
b[j]=temp;
}
} } System.out.println("first");
for(int k=0;kd[j])
{
char temp=d[i];
d[i]=d[j];
d[j]=temp;
}
} }
System.out.println("Second");
for(int k=0;k<b.length;k++)
{
System.out.println(d[k]);
}

int count=0;

for(int i=0;i<d.length;i++)
{
if(b[i]!=d[i])
{
System.out.println("It's not Anagram");
count=1;
break;

}
}
if(count==0)
{
System.out.println("It's Anagram");
}

}
}

Swing in the rain said...

Solution given by @Nitin Vashisth fails in repeated letters test case.
Eg: word1 = "abc";
word2 = "bbc";

Because HashSet never keeps the duplicate data.
The Best way to deal with this problem is only by sorting.

Chris S. said...

Seems like there's a way easier way than the problem described here, that would be solved in way less time.

Create an int array 26 long. For each letter in the string (string.charAt(i)) add 1 to the letter corresponding in int array ('e' or 'E' = array[5]).

For string 2, subtract one each time.

It's an anagram if the array is all zeroes at the end.

This is solved in O(n) time and O(1) space. As opposed to sorting them which is O(nLog(n)) at best.

Anonymous said...

s1='abcd'
s2='dabc'

if sorted(s2)==sorted(s1):
print 'anagram'
else:
print 'not anagram'

#less time complexity

def findAnagram(s1,s2):
c1=[0]*26
c2=[0]*26

for i in range(len(s1)):
position=ord(s1[i])-ord('a')
c1[position]+=1
for i in range(len(s2)):
position=ord(s2[i])-ord('a')
c2[position]+=1
if c1==c2:
print 'anagrams'
else:
print 'not anagrams'

findAnagram("abcdx","dabcx");

MyserY said...

I do this in O(n) and space O(1), the trick is use xor gates.
public static boolean isAnagram(String word, String anagram){
if (word.length() != anagram.length())
return false;

int xorGate = 0; //Xor gate is special for check ocurrences A^B^A == B also A^A == 0
for (int i = 0; i < word.length(); i++) {
xorGate ^= word.charAt(i)^anagram.charAt(i);
}
return xorGate == 0;
}

Cherss

MyserY said...

i have a bug in my last post, i fixx it whit 2 xor and some logics.
public static boolean isAnagram(String word, String anagram)
{
if (word.length() != anagram.length())
return false;
int xorGateW = 0; //Xor gate is special for check ocurrences A^B^A == B also A^A == 0
int xorGateA = 0; //Xor gate is special for check ocurrences A^B^A == B also A^A == 0
for (int i = 0; i < word.length(); i++) {
xorGateW ^= word.charAt(i);
xorGateA ^= anagram.charAt(i);
}
if (xorGateW != 0 || xorGateA != 0)
return (xorGateW^xorGateA) == 0;
else
return (xorGateW != 0 && xorGateA == 0) ||
(xorGateW == 0 && xorGateA != 0);
}
whit this test like assertFalse(StringAnagram.isAnagram("ffff", "aaaa")) will pass.

MyserY said...

i get other solution similar to mapreduce solutions ...
public static boolean anAnagram(String word, String anagram)
{
if (word.length() != anagram.length())
return false;
Map mapW = new HashMap<>();
Map mapA = new HashMap<>();
for (int i = 0; i < word.length(); i++) {
incrementMap(mapW, word.charAt(i));
incrementMap(mapA, anagram.charAt(i));
}
return mapW.entrySet().equals(mapA.entrySet());
}

private static void incrementMap(Map map, Character c) {
if (map.containsKey(c))
map.put(c, map.get(c)+1);
else
map.put(c, 1);
}

Anonymous said...

import java.util.*;
class anagram
{
public static void main(String args[])
{
Scanner in=new Scanner (System.in);
char p=' ';String s=" ";int c=0;
System.out.println("Enter a string:");
String str1=in.nextInt();
System.out.println("Enter another String:");
String str2=in.nextInt();
int l1=str1.length();
int l2=str2.length();
if(l1>l2)
{
for(int i=0;i='a' && p<='z' || p>='A' && p<='Z')
s=s+p;
}
l2=s.length();
}
else
{
for(int i=0;i='a' && p<='z' || p>='A' && p<='Z')
s=s+p;
}
l1=s.length();
}
if(l1==l2)
{
for(int i=0;i<l2;i++)
{
p=s.charAt(i);
for(int j=0;j<l2;j++)
{
m=s.charAt(j);
if(p==m)
c=1;
break;
else
c=0;
}
if(c==0)
break;
}
}
if(c==l1)
System.out.println("Anagram");
else
System.out.println("Not Anagram");
}
}

javin paul said...

@Anonymous, what is the time complexity of this solution? Also its better if you encapsulate the logic of checking anagram into a separate method e.g. isAnagaram(String input), combining with user input and test code is not a good idea.

MyserY said...

@Anonymous I see some problems in your code,
Excample you iterate 2 times when if(l1>l2) that not is necesary, if l1 != l2 you can said it is not anagram. Also your iteration have sintaxis problems. check it.
If you do that only for check the input, that you can check whit an regular expretion.
You complexity is to high, you iterate in worst case O(N+N*N).@Jarvin Paul.
Other recomendation is put more good names to variables. if some need read your code that is paintfull.

javin paul said...

@MyserY, Great inputs. Indeed, good variable name is must, a good refresher on naming best practices can be found here

srinidhi said...

In python 2.7
def anagra(a,b):
l1 = sorted(list(a))
l2 = sorted(list(b))
if l1 == l2:
print "anagram"
if __name__ == '__main__':
anagram(raw_input("Enter first word:"), raw_input("Enter second word:"))

sahil mohindroo said...

use hashmap - best time complexity

Anonymous said...

Bona....Simple way
public static void checkStringAnagram(String word, String anagram) {
char[] firstWord = word.toCharArray();
for (char letter : firstWord) {
anagram = anagram.replace(letter,' ');
}
System.out.println(anagram.trim().length() == 0 ? true : false);
}

Unknown said...

@Mysery Your xor solution is wrong:

It is failing for the following condition:

word = "xaaddy"
anagram="xbbccy"

Anonymous said...

package StringPackage;

import java.util.HashMap;
import java.util.Set;
import java.util.Map.Entry;

public class Anagram {
public static void main(String[] args) {
Anagram obj = new Anagram();
String word1 = "vinayak";
String word2 = "kayaniv";
char[] ch1 = word1.toCharArray();
char[] ch2 = word2.toCharArray();

HashMap hmap1 = new HashMap();
for (char c1 : ch1) {

if (hmap1.containsKey(c1)) {
hmap1.put(c1, hmap1.get(c1) + 1);
} else
hmap1.put(c1, 1);
}

HashMap hmap2 = new HashMap();
for (char c2 : ch2) {

if (hmap2.containsKey(c2)) {
hmap2.put(c2, hmap2.get(c2) + 1);
} else
hmap2.put(c2, 1);
}

Set> entry1 = hmap1.entrySet();
Set> entry2 = hmap2.entrySet();
if (entry1.size() == entry2.size()) {
for (Entry set1 : entry1) {
for (Entry set2 : entry2) {
if (set1.getKey() == set2.getKey()) {
if (set1.getValue() == set2.getValue()) {
System.out.println("anagarm");
break;
} else {
System.out.println("not anagram");
}
}
}
}

}
else
System.out.println("not anagram");
}
}

Anonymous said...

i can break the sort method version..... "bigcat" and "catbig" pass as an anagram

Unknown said...

@nitin vashishtha code breaks with "jjjava" and "vaaaja"
these two strings are not anagram according to me.correct me if I am wrong.

TabletZaSvakog said...

you can just concat them and use palindrome test:

public static boolean testPali(String str1, String str2) {
if(str1.length() != str2.length()){
return false;
}
String str = str1.concat(str2);
int n = str.length();
for (int i = 0; i < n / 2; ++i) {
if (str.charAt(i) != str.charAt(n - i - 1)) return false;
}
return true;
}

Nitesh Shrivastava said...

I used maps. I converted both String into Char array and then created maps for each arrays. To cofirm, they are anagram I comparedt the maps using Map.equals function. Below is the code:

private static void checkIfAnagram(String str1, String str2) {

// Convert string into Char array
char[] a1 = str1.toCharArray();
char[] b1 = str2.toCharArray();

// Create 2 Maps
Map map1 = new HashMap<>();
Map map2 = new HashMap<>();

// Put characters into Map with number of occurrence
// Map 1
for (char a : a1) {
map1.put(a, map1.getOrDefault(a, 0) + 1);
}
// Map 2
for (char b : b1) {
map2.put(b, map2.getOrDefault(b, 0) + 1);
}

// Compare 2 maps to confirm if the strings are anagram or not
if (map1.equals(map2)) {
System.out.println("String 1: '" + str1 + "' and 2: '" + str2 + " are anagrams");
} else {
System.out.println("String 1: '" + str1 + "' and 2: '" + str2 + " are not anagrams");
}
}

public static void main(String[] args) {
checkIfAnagram("aaas", "asa");
checkIfAnagram("aaasaaaaddsew", "aaasadaaadsew");
checkIfAnagram("akishna", "anhkais");
}

Paul Dasari said...



I made an ASCII conversion and sorted and compared the arrays to do the check.
import java.util.Arrays;

public class CheckAnagram {

public static void main(String[] args) {
// TODO Auto-generated method stub
String inp1="MARY".toUpperCase();
String inp2="ARMY".toUpperCase();
int in1[]= new int[inp1.toCharArray().length];
int in2[]= new int[inp2.toCharArray().length];
for (int i =0;i<inp1.toCharArray().length;i++){
in1[i]=(int)inp1.toCharArray()[i];
}
for (int i =0;i<inp2.toCharArray().length;i++){
in2[i]=(int)inp2.toCharArray()[i];
}
Arrays.sort(in1);
Arrays.sort(in2);
System.out.println(Arrays.equals(in1, in2));
}

}

Unknown said...

what about if String s ="Hello"; String s1="Hello"; can we talk about anagram? because the definition of anagram is: Two strings are called anagrams if they contain same set of characters but in different order. l suggest though about this case. thank you!!!

javin paul said...

@Amenkey, Indeed, that's a valid case, program should handle this case easily, did you checked?

Unknown said...

package javaapplication20;
import java.util.Scanner;
public class JavaApplication20 {
void CheckAnagram(){
Scanner sc=new Scanner(System.in);
int flag=0;
String s1,s2;
System.out.println("Enter the first string");
s1=sc.next();
System.out.println("Enter the second string");
s2=sc.next();
if(s1.length()==s2.length()){
for(int i=0;i<s1.length();i++){
for(int j=0;j<s2.length();j++){
if(s1.charAt(i)==s2.charAt(j)){
flag=1;
break;
}
}
break;
}
if(flag==1){
System.out.println("Yes Anagrams");
}else{
System.out.println("No");
}
}else{
System.out.println("Re-enter: Two strings must be of equal length");
CheckAnagram();
}
}
public static void main(String[] args) {

JavaApplication20 ja=new JavaApplication20();
System.out.println("Program to anagram strings");
ja.CheckAnagram();
}
}

Unknown said...

public class Anagrams {

public static void main(String[] args) {
// TODO Auto-generated method stub
String s="Hello";
String s1="oHlle";
Boolean flag=false;
if(s.length()!=s1.length())
{
System.out.println("string is not anagrams");
}else
{
for(int i=0;i-1)
{
flag=true;
}
else
{
flag=false;
break;
}

}
if(flag)
{
System.out.println("It's Anagram");
}else
{
System.out.println("It's not Anagram");
}

}
}

}

Unknown said...

import java.io.*;
class Jmp
{
public static void main(String args[])throws Exception
{
int c=0;
System.out.println("Enter the two string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String a=br.readLine();
String b=br.readLine();
if(a.length()==b.length())
{
System.out.println("jai ho");
while(b.length()>0)
{
//c=0
for(int i=0;i<a.length();i++)
{
if(b.charAt(0)==a.charAt(i))
{
c=c+1;
}
}
String[]k=b.split(b.charAt(0)+"");
b=new String("");
for(int j=0;j<k.length;j++)
b=b+k[j];
}


}
if(c==a.length())
{
System.out.println("anagram");
}
else
System.out.println("not anagram");


}
}

Deepak Mittal said...

/**
* Created by Deepak Mittal on 3/29/2018.
*/
public class AnagramLearn {

public static void main(String args[]){


int check = checkAnagarm("mkin","tuki");

if(check==-1){
System.out.println("Not Possible" );
}
else {
System.out.println("Char Needed: " + check);
}
}


public static int checkAnagarm(String a1,String a2){

if(a1.length()!=a2.length() ){
return -1;
}
int counter=0;
for (int i=0; i<a1.length();i++ ) {

if(!a2.contains(a1.charAt(i)+"" )){
counter++;
}

}
return counter;
}
}

Najstariji zanatlija said...

String input = "AnavoliMilovana";
final int length = input.length();
boolean anagram = true;
for (int i = 0; i < length; i++) {
char a = input.toLowerCase().charAt(i);
char b = input.toLowerCase().charAt(length - i - 1);
if (a != b) {
anagram = false;
break;
}
}
System.err.println((anagram ? "Yes, it is an" : "No, it's not an ") + "anagram ? ");

Unknown said...

``
public boolean isAnagram(String s1, String s2) {
int count[] = new int[256];

for (char c : s1.toCharArray()) count[c]++;
for (char c : s2.toCharArray()) count[c]--;

for (int c : count) {
if (c != 0) return false;
}
return true;
}
``

Unknown said...

String s1 = "nash";
String s2 = "shan";
int s1as = 0, s2as = 0;

for (int i = 0; i < s1.length(); i++) {

s1as = s1as + (int) s1.charAt(i);

}
for (int i = 0; i < s2.length(); i++) {

s2as = s2as + (int) s2.charAt(i);
}

if (s2as == s1as) {
System.out.println("strings are anagrams");
} else {
System.out.println("strings are not anagrams");
}

Unknown said...

package pracon;
import java.util.Scanner;

public class anagram {

public static void main(String[] args) {
Scanner in=new Scanner(System.in);

System.out.println("Enter first string");
String x=in.nextLine();
String x1=x.toLowerCase();
char[] t=x1.toCharArray();
int count=0;
boolean c=false;

System.out.println("Enter second string");
String y=in.nextLine();
String y1=y.toLowerCase();
char[] s=y1.toCharArray();

for(int a=0;a0)
{
System.out.println("The Strings are not an Anagram");
}
if(count==0)
{
System.out.println("The Strings are an Anagram");
}

}
}

Unknown said...

Wrong

JeanniusDev said...

The way to do it in linear time is to have two maps, one for each string. The map will have characters as keys and number of occurrences as values. First make sure strings are of same length if not return false. Next build map for each string.
Then iterate through the key of one map with enhanced for loop and get value, if value for same key is not same in the other map (or key is not present ) return false.
After iteration, return true

Anonymous said...

short and then compare

Ankush Arora said...

For strings with same case i.e both lower or upper. Solution is simple 1.e 1 for loop after sorting 2 string arrays or any other collection logic.

For Strings having 1 small case and other mixture of upper and lower case. find below solution.

Set sett = new HashSet();
sett.add('a');
sett.add('b');
sett.add('c');
sett.add('d');


String str = "CDab";
for(char c : str.toCharArray()) {
if(sett.contains(c) || sett.contains((char)((int)c+32))) {
System.out.println("Anagram");
}
else
System.out.println("Not Anagram");


}

Anonymous said...

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

public class Anagram {
static Map baseMap = new HashMap();
static Map childMap = new HashMap();
public static void main(String args[]){
String name="sdffdsfsdfsd";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
anagranCheck("mary","mary");
}


private static void anagranCheck(String anagram1,String anagram2) {

char[] ch;
ch = anagram1.toCharArray();
mapping(ch);
ch = anagram2.toCharArray();
mapping1(ch);
comapareMaps();
}

private static void mapping(char[] ch) { // Mapping functionality
for (Character c: ch) {
if(baseMap.containsKey(c))
baseMap.put(c, baseMap.get(c) + 1);
else {
baseMap.put(c, 1);
}
}

}
private static void mapping1(char[] ch) { // Mapping functionality
for (Character c: ch) {
if(childMap.containsKey(c))
childMap.put(c, childMap.get(c) + 1);
else {
childMap.put(c, 1);
}
}

}

private static void comapareMaps() {
if(baseMap.keySet().equals(childMap.keySet())) {
System.out.println("yes Same");
}else {
System.out.println("not Same");

}
}
}

sachit said...

package StringGames;

public class HowtocheckiftwoStringsareanagramsofeachother {
static int cnt=0;
public static void main (String[] args) {
char[] ana1="edan".toCharArray();
char[] ana2="naed".toCharArray();

for (int i = 0; i < ana1.length; i++) {
for (int j = 0; j < ana2.length; j++) {

if(ana1.length==ana2.length)
if(ana1[i]==ana2[j])
cnt++;
}
}

if(cnt==ana1.length)
System.out.println("Strings are Anagram to each others.");
}
}

Anonymous said...

import java.util.Arrays;

/**
* If two Strings have same length and contain same characters and written in
* same-case, then these String are anagram to each other. For ex: LISTEN &
* SILENT, ARMY & MARY
*
* @author Prem Nath
*
*/
public class Anagram {

public static void main(String[] args) {
String string1 = "LISTEN";
String string2 = "SILENT";

// Step 1: Check if both String are of same length, if yes then proceed to Step 2, otherwise they are not anagram
if (string1.length() != string2.length()) {
System.out.println("Not Anagram!");
} else {
// Step 2: Sort both String
string1 = sortString(string1);
string2 = sortString(string2);

// Step 3: Check if both Strings are equal, if not then they are not anagram
if (!string1.equals(string2)) {
System.out.println("Not Anagram!");
} else {
System.out.println("Yes Anagram!");
}
}

}

public static String sortString(String str) {
if (str.isEmpty()) {
return "";
} else {
char[] characters = str.toCharArray();
Arrays.sort(characters);

String s = "";
for (char c : characters) {
s = s + c;
}
return s;
}
}

}

Unknown said...

I have a solution

package com.dk.task;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Anagrams {

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);
System.out.println("enter the first string");
String text1=sc.next().toUpperCase();
System.out.println("enter the second string");
String text2=sc.next().toUpperCase();
int count1=0,count2=0;

char[] ch1=text1.toCharArray();
char[] ch2=text2.toCharArray();

for(Character c:ch1) {
count1=count1+c;

}
for(Character c:ch2) {
count2=count2+c;

}
if(count1==count2)
System.out.println("anagrAMS");
else
System.out.println("not anagrams");


}

}

srinu said...

package com.pageTest;

import java.util.*;
import java.util.stream.Collectors;

public class DuplicateCharacters {

private Map anagram(String string) {

int counter = 0;
Map characters = new HashMap();
char chars[] = string.toUpperCase().toCharArray();
for (int i = 0; i < chars.length; i++) {

for (int j = 0; j < chars.length; j++) {
if (chars[i] == chars[j]) {
counter++;

}
}
characters.put(chars[i], counter);
counter = 0;
}
return characters;
}

public static void main(String[] args) {
DuplicateCharacters duplicateCharacters = new DuplicateCharacters();
Map string1 = duplicateCharacters.anagram("programming");
Map string2 = duplicateCharacters.anagram("PROGRAMMING");

if(string1.size()==string2.size()){

int counter = string1.keySet().stream().filter(x-> !string1.get(x).equals(string2.get(x)))
.collect(Collectors.toList()).size();
if(counter==0){
System.out.println("Anagram");
}else{
System.out.println("Not Anagram");
}

}else{
System.out.println("Not Anagram");
}

}
}

Unknown said...

public static void main(String[] args) {

String s="india";

String s2="adini";


int flag=0;

char[] c1=s.toCharArray();
char[] c2=s2.toCharArray();

if(c1.length!=c2.length) {

System.out.println("Not anagram");
}

else {
Arrays.sort(c1);
Arrays.sort(c2);

for(int i=0;i<c1.length;i++) {

if(c1[i]==c2[i]) {
continue;
}

else {
flag=1;
break;
}

}
if(flag==0)
System.out.println("Anagram");
else
System.out.println("Not anagram");

}


}

Richa Jain said...

Using contains mehtod check string anagram.

public class StringAnagram {
public static void main(String args[]) {

String str = "SLEEP";
String str2 = "SLEP";
char c1[] = str.toCharArray();
Boolean b = true;
if(str.length()==str2.length()) {
for(char c : c1) {
if(!str2.contains(c+"")) {
b=false;
break;
}
}
}else {
b=false;
}

if(b) {
System.out.println("anagram");
}else {
System.out.println("not anagram");
}
}
}

javin paul said...

Hello Richa,
Good job, a couple of tips to make it even better
1. use meaningful name, instead of "b" call it "isAnagram"

Anonymous said...

@Richa
what if
str = "hhhh"
str2 = "hello"

when you iterate over str then 'h' is always inside of str2 so it will return true.
although these are not anagrams

Unknown said...

String str1 = "Ar my".toLowerCase();
String str2 = "ma ry".toLowerCase();
str1.replaceAll("\\s", "");
str2.replaceAll("\\s", "");

char[] array1 = str1.toCharArray();
char[] array2 = str2.toCharArray();
Arrays.sort(array1);
Arrays.sort(array2);

System.out.println(Arrays.equals(array1, array2));

Unknown said...

package CollectionDemo;

public class AnagramCheck {

public static void main(String[] args) {
// TODO Auto-generated method stub

String s1="caer";
String s2="acre";
int res=0;
char[] ch1=s1.toCharArray();
char[] ch2=s2.toCharArray();
if(s1.length()!=s2.length())
{
System.out.println("Strings are not Anagram");
}
else
{
for(int i=0;i<ch1.length;i++)
{
String j = Character.toString(ch1[i]);
String j1 = Character.toString(ch2[i]);
if(s2.contains(j) && s1.contains(j1))
{
res=1;

}
else
{
res=0;
break;
}

}
if(res!=1)
{
System.out.println("String "+s1+" and String "+s2+" are not Anagram");
}
else
{
System.out.println("String "+s1+" and String "+s2+" are Anagram");
}

}

}

}

Post a Comment