有效的字母异位词

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

示例 1:

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

示例 2:

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

说明:
你可以假设字符串只包含小写字母。

进阶:
如果输入字符串包含 unicode 字符怎么办?你能否调整你的解法来应对这种情况?

代码

使用一个数组统计小写字母出现的次数是否抵消(穷举法)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public boolean isAnagram(String s, String t) {
//长度不相等,直接返回false
if (s.length() != t.length()) return false;
int length = s.length();
//统计数组
int[] ints = new int[26];
char[] chars1 = s.toCharArray();
char[] chars2 = t.toCharArray();
for (int i = 0; i < length; i++) {
//s字符串中的字符出现+1
ints[chars1[i] - 97] += 1;
//t字符串中的字符出现-1
ints[chars2[i] - 97] -= 1;
}
for (int i : ints) {
//如果未抵消完,则为false
if (i != 0) return false;
}
return true;
}

进阶

处理unicode字符要使用HashMap,因为不适合穷举呀

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) return false;
int length = s.length();
char[] chars1 = s.toCharArray();
char[] chars2 = t.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
for (int i = 0; i < length; i++) {
char c = chars1[i];
//merge适用于两种情况。如果给定的Key值不存在,它就变成了put(key, value)。
//但如果所述Key已经存在一些值,remappingFunction 可以操作合并:
//只需返回新值覆盖旧值: (old, new) -> new
//只需返回旧值保留旧值: (old, new) -> old
//以某种方式合并两者,例如: (old, new) -> old + new
//甚至删除旧值: (old, new) -> null
map.merge(c, 1, (a, b) -> a + b);
c = chars2[i];
map.merge(c, -1, (x, y) -> x + y);
}
//判断是否抵消完成,并返回相应的结果
return map.entrySet().stream().noneMatch(x -> x.getValue() != 0);
}