242. Valid Anagram

Question

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Thinking:

  • Method 1:类似使用MAP来存储出现次数
class Solution {
    public boolean isAnagram(String s, String t) {
        int[] count = new int[26];
        int sLen = s.length();
        int tLen = t.length();
        if(sLen != tLen) return false;
        for(int i = 0; i < sLen; i++)
            count[s.charAt(i) - 'a']++;
        for(int i = 0; i < tLen; i++)
            count[t.charAt(i) - 'a']--;
        for(int i = 0; i < 26; i++)
            if(count[i] != 0) return false;
        return true;
    }
}

Second time

  1. Since it mentions that only unicode will be included, so I used a array as a map.
    class Solution {
     public boolean isAnagram(String s, String t) {
         int[] count = new int[256];
         char[] sArr = s.toCharArray();
         for(int i = 0; i < sArr.length; i++){
             count[sArr[i]]++;
         }
         char[] tArr = t.toCharArray();
         for(int i = 0; i < tArr.length; i++){
             count[tArr[i]]--;
         }
         for(int i = 0; i < 256; i++){
             if(count[i] != 0) return false;
         }
         return true;
     }
    }
    

Amazon session

class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length() != t.length()) return false;
        int[] arr = new int[26];
        int count = 0;
        for(char c: s.toCharArray()){
            if(arr[c - 'a'] == 0) count++;
            arr[c - 'a']++;
        }
        for(char c: t.toCharArray()){
            arr[c - 'a']--;
            if(arr[c - 'a'] < 0) return false;
            if(arr[c - 'a'] == 0) count--;
        }
        return count == 0;
    }
}