Checking to see if the permutation is correct – Java

Within the array there is three words to be checked to see if there permutation is correct. If it is correct it will print out true likewise if it is false it will print out false.

public class Permutation
{
    public static boolean permutation(String s, String t)
    {
        //if the two words are not the same length then they clearly are not a permutation
        if (s.length() != t.length())
        {
            return false;
        }//if

        int[] letters = new int[256];

        char[] s_array = s.toCharArray();

        for (char c : s_array)
        {
            // count number of each char in s.
            letters[c]++;
        }//for

        for (int i = 0; i < t.length(); i++)
        {
            int c = (int) t.charAt(i);
            if (--letters[c] < 0)
            {
                return false;
            }//if
        }//for

        return true;
    }//permutation

    public static void main(String[] args)
    {
        String[][] pairs = {{"apple", "papel"}, {"carrot", "tarroc"}, {"hello", "llloh"}};
        for (String[] pair : pairs)
        {
            String word1 = pair[0];
            String word2 = pair[1];
            boolean anagram = permutation(word1, word2);
            System.out.println(word1 + ", " + word2 + ": " + anagram);
        }//for
    }//main
}//class

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s