242 有效的字母异位词

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

示例1:

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

示例2:

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

说明:

1
你可以假设字符串只包含小写字母。

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
方法一:
public boolean isAnagram(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null || t == null) {
return false;
}
Map<Character, Integer> mapS = new HashMap<>();
Map<Character, Integer> mapT = new HashMap<>();

for (int i = 0; i < s.length(); i++) {
if (mapS.containsKey(s.charAt(i))) {
mapS.put(s.charAt(i), mapS.get(s.charAt(i)) + 1);
} else {
mapS.put(s.charAt(i), 1);
}
}

for (int i = 0; i < t.length(); i++) {
if (mapT.containsKey(t.charAt(i))) {
mapT.put(t.charAt(i), mapT.get(t.charAt(i)) + 1);
} else {
mapT.put(t.charAt(i), 1);
}
}

if (mapS.equals(mapT)) {
return true;
}
return false;
}

方法二:
public boolean isAnagram(String s, String t) {
if (s == null && t == null) {
return true;
}
if (s == null || t == null) {
return false;
}
if(s.length() != t.length()){
return false;
}
char[] ss = s.toCharArray();
char[] tt = t.toCharArray();

Arrays.sort(ss);
Arrays.sort(tt);

return Arrays.equals(ss,tt);
}

思路:

1
2
方法一使用map
方法二使用Arrays类的特性