持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第11天,点击查看活动详情
一、题目描述:
给定两个字符串 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 * 10^4
- s 和 t 仅包含小写字母
进阶: 如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?
二、思路分析:
题目的意思进行阅读理解,顺序颠倒后的字符串中字符出现次数相同。这个就使用一个int array作为map就可以。 定义一个int array,首次遍历记录s中出现的字符的个数,再次遍历t,不断减少map中字符的次数,一旦出现一个字符不在s中,返回false。 我们还需要一个count,来记录t中出现的某个字符的字数,比如AAB,count = 2
三、AC 代码:
class Solution {
public boolean isAnagram(String s, String t) {
// count freq
int[] map = new int[256];
int count = 0; // count diff type of chars
for (char ch : s.toCharArray()) {
if (map[ch] == 0) count++;
map[ch]++;
}
for (char ch : t.toCharArray()) {
if (map[ch] > 0) {
map[ch]--;
if (map[ch] == 0) count--;
} else {
// s.length > t.length case
// s = "a", t = "ab"
return false;
}
}
if (count == 0) return true;
else return false;
}
}
四、参考:
ACM 选手图解 LeetCode 有效的字母异位词 | 编程文青李狗蛋 - 有效的字母异位词 - 力扣(LeetCode)