Wednesday, December 25, 2013

Program to check if two string are anagrams.

//There are two ways to do this.
//1.Sort both the strings and check if both of them are equal;

   public boolean isStringsAreAnagrams(String source, String target){
        if(null == source  || null == target){
            return false;
        }
        return (source.isEmpty() && target.isEmpty()) || (sort(source).equals(sort(target)));
    }
    //Insertion Sort
    public String sort(String source)
    {
        char temp_char;
        int j;
        char[] sourceInCharArray = source.toCharArray();
        for(int i = 0; i < sourceInCharArray.length ; i++){
            j = i - 1;
            temp_char = sourceInCharArray[i];
            while(j >= 0 && temp_char < sourceInCharArray[j]){
                sourceInCharArray[j + 1] =  sourceInCharArray[j];
                j--;
            }
            sourceInCharArray[j + 1] = temp_char;   
        } 
        return new String(sourceInCharArray);
    }
//2.Check if the count of each unique characters in both the Strings are same.
//Program upcoming.

No comments:

Post a Comment