Java solution using arrays, 9ms


  • 0
    public class Solution {
        public boolean isAnagram(String s, String t) {
            if (s.length() != t.length()) return false;
    
            int OFFSET = 97;
            int ARRAY_SZ = 26;
            int[] s_arr = new int[ARRAY_SZ];
            int[] t_arr = new int[ARRAY_SZ];
    
            for (int i = 0; i < s.length(); i++) {
                int s_idx = ((int)s.charAt(i)) - OFFSET;
                s_arr[s_idx] = s_arr[s_idx] +1;
                
                int t_idx = ((int)t.charAt(i)) - OFFSET;
                t_arr[t_idx] = t_arr[t_idx] +1;
            }
            
            for(int j=0; j<ARRAY_SZ; j++){
                if(s_arr[j] != t_arr[j]) return false;
            }
            return true;
        }
    }
    ``

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.