Checking Anagram of a String array input

泪湿孤枕 提交于 2019-12-23 04:26:05

问题


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?


回答1:


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 



回答2:


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.




回答3:


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;
    }          
}



回答4:


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



来源:https://stackoverflow.com/questions/27393141/checking-anagram-of-a-string-array-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!