158 · Valid Anagram - LintCode

# Description

Write a method anagram(s,t) to decide if two strings are anagrams or not.

What is Anagram?

  • Two strings are anagram if they can be the same after change the order of characters.

# Example

Example 1:

Input: s = "ab", t = "ab"
Output: true

Example 2:

Input:  s = "abcd", t = "dcba"
Output: true

Example 3:

Input:  s = "ac", t = "ab"
Output: false

Challenge

O(n) time, O(1) extra space

# Solution

public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    public boolean anagram(String s, String t) {
        int[] countS = new int[256];
        int[] countT = new int[256];
        for(int i = 0; i < s.length(); i++){
            countS[s.charAt(i)]++;
        }
         for(int i = 0; i < t.length(); i++){
            countT[t.charAt(i)]++;
        }
        for (int i = 0; i < 256; i++){
            if (countS[i] != countT[i]){
                return false;
            }
        }
    return true;
    }
}

# HashMap

public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    public boolean anagram(String s, String t) {
        Map<Character, Integer> hm = new HashMap<>();
        for (char c : s.toCharArray()) {
           hm.put(c, hm.getOrDefault(c, 0) + 1);
        }
        for  (char c : t.toCharArray()) {
            if (hm.containsKey(c)) {
                hm.put(c, hm.get(c) - 1);
                if (hm.get(c) == 0) {
                    hm.remove(c);
                }              
            } else {
                return false;
            }
        }
        return hm.isEmpty();
    }
}```