Monday, July 17, 2017

Write a method to decide if two strings are anagrams or not.


/**
 * Problem :- Write a method to decide if two strings are anagrams or not.
 */
public class TwoStringAnagrams {
    /*
        Take character arrays of both strings, sort them and check if they are same if not the character
        arrays are not anagrams
     */
    boolean anagram(String s, String t) {
        char[] sc = s.toCharArray();
        char[] tc = t.toCharArray();
        Arrays.sort(sc);
        Arrays.sort(tc);
        return Arrays.equals(sc, tc);
    }

    /*
        Generate character frequency count map for first string and then use the second string to reduce
        frequency
     */
    boolean anagram2(String s, String t) {
        Map charCount = new HashMap<>();
        char[] sChar = s.toCharArray();
        for(int i = 0 ; i < sChar.length ;i++){
            char currentChar = sChar[i];
            if(charCount.containsKey(currentChar)){
                charCount.put(currentChar,charCount.get(currentChar)+1);
            }else{
                charCount.put(currentChar,1);
            }
        }

        char[] tChar = t.toCharArray();
        for(int i = 0 ; i < tChar.length ; i++){
            char currentChar = tChar[i];
            if(charCount.containsKey(currentChar)){
                charCount.put(currentChar,charCount.get(currentChar)-1);
                if(charCount.get(currentChar) == 0)
                    charCount.remove(currentChar);
            }else{
                return false;
            }

        }
        return charCount.size() ==0;
    }
}

No comments:

Post a Comment