A method to determine if two string are anagrams, will return true if the strings are the same - Java Data Structure

Java examples for Data Structure:Algorithm

Description

A method to determine if two string are anagrams, will return true if the strings are the same

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String s1 = "java2s.com";
        String s2 = "java2s.com";
        System.out.println(areAnagrams(s1, s2));
    }//from  www .  j av a2s.c  o  m

    /**
     * A method to determine if two string are anagrams, will return true if the
     * strings are the same
     * 
     * @param s1
     * @param s2
     * @return true if the two input words are anagrams and false if otherwise
     */
    public static boolean areAnagrams(String s1, String s2) {
        // Compare the sorted strings
        return sort(s1).equals(sort(s2));
    }

    /**
     * Sorts each character of a string parameter using insertion sort
     * 
     * @param myString
     * @return the sorted version of the input string as a string
     */
    public static String sort(String myString) {

        if (myString.length() == 0) {
            return "";
        } else {
            // Sort should not be case sensitive
            myString = myString.toLowerCase();
            // Calls the helper method to get an array of chars
            char[] myWord = toArray(myString);

            // Do the insertion sort
            for (int i = 1; i < myWord.length; i++) {
                int j;
                for (j = i - 1; j >= 0 && (myWord[j] >= myString.charAt(i)); j--) {
                    myWord[j + 1] = myWord[j];
                }
                myWord[j + 1] = myString.charAt(i);
            }
            String finalWord = "";
            // Read the sorted characters of myWord into finalWord
            for (int i = 0; i < myWord.length; i++) {
                finalWord += myWord[i];
            }
            return finalWord;
        }
    }

    /**
     * A helper method used when sorting a word
     * 
     * @param myString
     * @return an array of chars containing all of the characters of the input
     *         string
     */
    private static char[] toArray(String myString) {

        char[] charList = new char[myString.length()];
        // Saves each letter in the word in the char array
        for (int i = 0; i < myString.length(); i++) {
            charList[i] = myString.charAt(i);
        }
        return charList;

    }
}

Related Tutorials