Thursday, October 20, 2011

String : Anagrams or not

Question : Find if two words are anagrams or not.

Solution :
The best solution basically involves sorting the characters in the words and then comparing to check if they are same.

public static boolean isAnagram(String s1, String s2){
        if (s1.length() != s2.length() )
            return false;
        char s1array[] = s1.toLowerCase().toCharArray();
        char s2array[] = s2.toLowerCase().toCharArray();
        for (int i=0;i <s1.length();i++)
            if (s1array[i] != s2array[i])
                return false;
        return true;

No comments:

Post a Comment