242.有效的字母异位词——学习笔记

发布时间 2023-04-12 22:22:54作者: 会飞的笨笨

题目:给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。

注意:若 s 和 t 中每个字符出现的次数都相同,则称 s 和 t 互为字母异位词。

示例1

输入: s = "anagram", t = "nagaram"
输出: true

示例2

输入: s = "rat", t = "car"
输出: false

提示

  • 1 <= s.length, t.length <= 5 * 104
  • s 和 t 仅包含小写字母

题目来源:力扣(LeetCode)
链接

题解

class Solution {
    public static boolean isAnagram(String s, String t) {
        //定义一个数据用来存放每个字母的个数
        int[] record = new int[26];
        //遍历s,取出每一个字符,把数量保存在数组中
        for (int i = 0; i < s.length(); i++) {
            record[s.charAt(i) - 'a']++;
        }
        //遍历t,从数组中取出每一个数组,记录取出的个数
        for (int i = 0; i < t.length(); i++) {
            record[t.charAt(i) - 'a']--;
        }
        //如果数组中有元素不为0,说明存在字符出现的次数不相同的情况
        for (int count : record) {
            if (count != 0) {
                return false;
            }
        }
        return true;
    }
}