242. 有效的字母异位词

难度简单347
给定两个字符串 st ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1:
输入: s = “anagram”, t = “nagaram”
输出: true

示例 2:
输入: s = “rat”, t = “car”
输出: false
说明:
你可以假设字符串只包含小写字母。
进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

  1. public boolean isAnagram(String s, String t) {
  2. if (s.length() != t.length()) {
  3. return false;
  4. }
  5. Map<Character, Integer> table = new HashMap<Character, Integer>();
  6. for (int i = 0; i < s.length(); i++) {
  7. char ch = s.charAt(i);
  8. table.put(ch, table.getOrDefault(ch, 0) + 1);
  9. }
  10. for (int i = 0; i < t.length(); i++) {
  11. char ch = t.charAt(i);
  12. table.put(ch, table.getOrDefault(ch, 0) - 1);
  13. if (table.get(ch) < 0) {
  14. return false;
  15. }
  16. }
  17. return true;
  18. }
  19. 作者:LeetCode-Solution
  20. 链接:https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/
  1. public boolean isAnagram(String s, String t) {
  2. if (s.length() != t.length()) {
  3. return false;
  4. }
  5. char[] str1 = s.toCharArray();
  6. char[] str2 = t.toCharArray();
  7. Arrays.sort(str1);
  8. Arrays.sort(str2);
  9. return Arrays.equals(str1, str2);
  10. }
  11. 作者:LeetCode-Solution
  12. 链接:https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/
  1. class Solution {
  2. public boolean isAnagram(String s, String t) {
  3. if (s.length() != t.length()) {
  4. return false;
  5. }
  6. int[] table = new int[26];
  7. for (int i = 0; i < s.length(); i++) {
  8. table[s.charAt(i) - 'a']++;
  9. }
  10. for (int i = 0; i < t.length(); i++) {
  11. table[t.charAt(i) - 'a']--;
  12. if (table[t.charAt(i) - 'a'] < 0) {
  13. return false;
  14. }
  15. }
  16. return true;
  17. }
  18. }
  19. 作者:LeetCode-Solution
  20. 链接:https://leetcode-cn.com/problems/valid-anagram/solution/you-xiao-de-zi-mu-yi-wei-ci-by-leetcode-solution/