### 题目

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

For example,

s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.


Note: You may assume the string contains only lowercase alphabets.

Follow up: What if the inputs contain unicode characters? How would you adapt your solution to such case?

### 用一个Map记录每个字母出现的次数

• time: $O(n)$
• space: $O(n)$

#### 代码

public class Solution {
public boolean isAnagram(String s, String t) {
Map<Character,Integer> freq = new HashMap<>();
int len = s.length();
if (t.length() != len) { return false; }
for (int i = 0; i < 26; i++) {
freq.put((char)(i+'a'),0);
}
for (int i = 0; i < len; i++) {
Character c = s.charAt(i);
freq.put(c,freq.get(c)+1);
}
for (int i = 0; i < len; i++) {
Character c = t.charAt(i);
freq.put(c,freq.get(c)-1);
}
for (Map.Entry<Character,Integer> entry : freq.entrySet()) {
if (entry.getValue() != 0) { return false; }
}
return true;
}
}


### 用数组记录字母出现的次数

• time: $O(n)$
• space: $O(n)$

#### Java代码

public class Solution {
public boolean isAnagram(String s, String t) {
int len = s.length();
if (t.length() != len) { return false; }
int[] freq = new int[26];
for (int i = 0; i < len; i++) {
freq[s.charAt(i)-'a']++;
freq[t.charAt(i)-'a']--;
}
for (int i = 0; i < 26; i++) {
if (freq[i] != 0) { return false; }
}
return true;
}
}


#### C代码

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

static bool isAnagram(char *, char *);

static bool isAnagram(char *s, char *t) {
int len = strlen(s);
if (strlen(t) != len) { return false; }
int freq[26] = {0}; // the local array will not be initialized to 0 if I declare by with "freq[26];"
for (int i = 0; i < len; i++) {
freq[*s++ - 'a']++;
freq[*t++ - 'a']--;
}
for (int i = 0; i < 26; i++) {
if (freq[i]) { return false; }
}
return true;
}


### 先排序

• time: $O(n\log_{}{n})$
• space: $0$