# 题目描述

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.

# 题目解答

#### 解题思路

• 先对字符数组排序，然后判断时候相等
• 建立小写字符的hash表

#### 代码实现

public class Solution {
public boolean isAnagram(String s, String t) {
if(s == null || t == null)
return false;
char[] s1 = s.toCharArray();
char[] t1 = t.toCharArray();
Arrays.sort(s1);
Arrays.sort(t1);

return Arrays.equals(s1, t1);
}
}

hash

public class Solution {
public boolean isAnagram(String s, String t) {
if(s == null || t == null)
return false;

if(s.length() != t.length())
return false;
//长度相等
int[] alpha = new int[26];
for(int i = 0; i < s.length(); i++){
alpha[s.charAt(i)-'a']++;
}

for(int i = 0; i < t.length(); i++){
//建立在长度相等的情况下
//存在小于0的情况就不是异位构词
if(--alpha[t.charAt(i)-'a'] < 0)
return false;
}
return true;
}
}

05-14 1982

08-05 1356

10-19 416

11-17 2146

08-02 6959

08-20 921

01-29 728

08-04 658

01-17 391

05-31 18