Valid Anagram – Java

   public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    public boolean anagram(String s, String t) {
        // write your code here
        if (s == null || t == null) {
            return false;
        }
        
        int[] cntS = new int[256];
        int[] cntT = new int[256];
        
        for (char c : s.toCharArray()) {
            cntS[c]++;
        }
        
        for (char c : t.toCharArray()) {
            cntT[c]++;
        }
        
        //Arrays.equals()
        for (int i = 0; i < 256; i++) {
            if (cntS[i] != cntT[i]) {
                return false;
            }
        } 
        return true;
    }
}

Time O(n). Space O(1).

Leave a comment

Design a site like this with WordPress.com
Get started