user2987894 user2987894 - 8 days ago 8
Java Question

How to find anagram for 2 Strings

I have written a Java program to find Anagram for 2 strings.

For Reference:
Two strings are anagrams if they are written using the same exact letters, ignoring space, punctuation and capitalization. Each letter should have the same count in both strings. For example, Army and Mary are anagram of each other.

Program:

package practice;

import java.util.ArrayList;
import java.util.List;

public class Anagram_String {

public static void main(String[] args) {

String s1="mary";
String s2="army";
int k=0;
List<String> matchedChar= new ArrayList<String>();
String charmatch="";

char[] ch1= s1.toLowerCase().toCharArray();
char[] ch2= s2.toLowerCase().toCharArray();

if(s1.length()==s2.length())
{

for(int i=0;i<s1.length();i++)
{
for(int j=0;j<s2.length();j++)
{
if(ch1[i]==ch2[j])
{
k++;
charmatch=String.valueOf(ch1[i]);
System.out.println(charmatch);
matchedChar.add(charmatch);
System.out.println("Arraylist value is "+matchedChar.toString());
System.out.println(matchedChar.size());
}
}

k=0;
}

String arrayValue=matchedChar.toString();
System.out.println("Array value is "+arrayValue);

if(arrayValue.contains(s2)){

System.out.println("String 1 and String 2 are anagrams of each other");

}
else
{
System.out.println("String 1 and String 2 are not anagrams of each other");
}

}

}

}


Output:

m
Arraylist value is [m]
1
a
Arraylist value is [m, a]
2
r
Arraylist value is [m, a, r]
3
y
Arraylist value is [m, a, r, y]
4
Array value is [m, a, r, y]
String 1 and String 2 are not anagrams of each other


Here if you see all the characters are added to to the arraylist but when compared with the string, it is showing the output as they are not anagrams of each other.

Kindly help me to find solution for this.

Thank you,

Answer

What I think is that your solution will work only for words with unique characters, and time complexity will be O(n^2) (where n - is the length of String).

However, there is a better solution for such problem:

  1. Take String.toCharArray() value for each string
  2. Sort those arrays
  3. If those arrays are equal, then your words are anagrams
Comments