0

This is my code below to check anagram of a given string array.
It always gives me false even in the simplest case with only one input.
I don't understand am I not converting string array into string correctly or my algorithm is plain wrong.

public class anagram
{
     static boolean isAnagram(String[] s1, String[] s2) { 
        String str = s1.toString();
        String str2 = s2.toString();
        if (str.length() != str2.length()) 
            return false;

        for (int i =0; i<str.length();i++)
        { 
            for (int j = 0;j<str2.length();j++)
            { 
                if (s1[i] == s2[j]) {
                    return true; 
                }
                return false; 
            }                   
        } 
        return true; 
    }

    public static void main(String [] args){
        String [] s1 = {"shot"};
        String [] s2 = {"host"};
        System.out.println(isAnagram(s1,s2));
    }
}

Can you please help me identify what is wrong?

almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
zydexo
  • 63
  • 5
  • 12

4 Answers4

0

Strings are not primitive variables in Java, therefore you must use the .equals() method instead of checking for equality using '==' to perform a thorough comparison.

Community
  • 1
  • 1
Mapsy
  • 4,192
  • 1
  • 37
  • 43
0

Your algorithm for checking seems to be a little incorrect.
Edited the isAnagram function here:

public static void main(String[] args)
{
    String s1 = "shotaabb";
    String s2 = "hostbaba";
    System.out.printf("String s1: %s, String s2: %s%n", s1, s2);
    System.out.println(isAnagram(s1, s2) ?
            "Is anagram" : "Is not an anagram");
}

static boolean isAnagram(String s1, String s2)
{
    String str1 = new String(s1);
    String str2 = new String(s2);

    // Ensures that both strings are of the same length
    if (str1.length() != str2.length())
        return false;

    int str1Len = str1.length();
    for (int i = 0; i < str1Len; i++)
    {
        int charIndex = str2.indexOf(str1.charAt(i));

        if(charIndex == -1) // Not found in str2
            return false;
        else
        {
            // Remove the character from str2
            str2 = str2.substring(0, charIndex) +
                str2.substring(charIndex + 1);
        }
    }

    return true;
}

What the code does is:

  • Gets a character from s1, finds the index of that character inside s2
  • If the index is -1, character not found inside s2, return false
  • If the character can be found inside s2, remove it from s2
  • At the end, if all characters inside s1 can be found in s2, return true
  • Based on the fact that both strings are of the same length, if all character in s1 can be found & removed from s2, s1 is an anagram of s2 & vice versa.

Output:

String s1: shotaabb, String s2: hostbaba
Is anagram


Update (Comparing String arrays):

String[] strArr1 = {"shot", "dcba"};
String[] strArr2 = {"host", "abcd"};

for(String s1 : strArr1)
{
    for(String s2 : strArr2)
    {
        System.out.printf("%nString s1: %s, String s2: %s%n", s1, s2);
        System.out.println(isAnagram(s1, s2) ?
            "Is anagram" : "Is not an anagram");
    }
}

Output for updated code:

String s1: shot, String s2: host
Is anagram

String s1: shot, String s2: abcd
Is not an anagram

String s1: dcba, String s2: host
Is not an anagram

String s1: dcba, String s2: abcd
Is anagram 
almightyGOSU
  • 3,731
  • 6
  • 31
  • 41
  • I appreciate that! but what if my input is String Array as mentioned above and not a string. – zydexo Dec 10 '14 at 04:26
  • Why would you compare 2 String array instead of 2 strings? I don't really get that. – almightyGOSU Dec 10 '14 at 04:27
  • It was given to me, i don't know maybe to make my life more stressful. – zydexo Dec 10 '14 at 04:31
  • That's interesting! Thanks for the help! Just for my curiosity, what do we do when isAnagram() has a string array input? How do we solve it then? convert string array to string there? – zydexo Dec 10 '14 at 04:48
  • If `isAnagram()` only returns a boolean, I don't think it will be of much use to pass in 2 String arrays? It will depend a lot on what you are trying to achieve with `isAnagram()` in my opinion. – almightyGOSU Dec 10 '14 at 05:13
0
public static bool IsAnagram(string firstString, string secondString)
{
    firstString = firstString.Replace(" ", "").ToLower();
    secondString = secondString.Replace(" ", "").ToLower();

    var firstStringArray = firstString.OrderBy(x => x);
    var secondStringArray = secondString.OrderBy(x => x);

    string s1 = new string(firstStringArray.ToArray());
    string s2 = new string(secondStringArray.ToArray());

    if (s1.Equals(s2))
    {
        return true;
    } else {
        return false;
    }          
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Abhishek Maurya
  • 519
  • 5
  • 8
0

To check if two String are anagram, case not sensitive, here the method:

public boolean isAnagram(String s1, String s2) {
    class SortChars{
        String sort(String source) {
            char[] chars = source.toLowerCase().toCharArray();
            Arrays.sort(chars);
            return new String(chars);
        }
    }
    SortChars sc = new SortChars();
    return sc.sort(s1).equals(sc.sort(s2));
}

The solution is taken from the book "cracking the coding interview", Authored by Gayle Laakmann McDowell

Enrico Giurin
  • 2,183
  • 32
  • 30