跳转至

242. Valid Anagram

Leetcode Hash Table Sort

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

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?

分析

确认错位词。可以使用两种方法,都非常简单

  1. 将字符串中的字符排序,然后一一比较字符是否相等
  2. 将字符串中的字符放到哈希表中分类计数,其中一个+1,另一个-1,最后都要等于0
public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;
    char[] sChar = s.toCharArray(), tChar = t.toCharArray();
    Arrays.sort(sChar);
    Arrays.sort(tChar);
    return Arrays.equals(sChar, tChar);
}

利用哈希表分类计数:

public boolean isAnagram(String s, String t) {
    if (s.length() != t.length()) return false;

    // 一共只有26个字母
    int[] count = new int[26];
    for (int i = 0; i < s.length(); i++) {
        count[s.charAt(i) - 'a']++;
        count[t.charAt(i) - 'a']--;
    }

    for (int num : count)
        if (num != 0) return false;

    return true;
}