forked from DreamCats/java-notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIsAnagram.java
More file actions
78 lines (72 loc) · 1.73 KB
/
IsAnagram.java
File metadata and controls
78 lines (72 loc) · 1.73 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package normal;
import java.util.HashMap;
/**
* @program JavaBooks
* @description: 242.有效的字母异位词
* @author: mf
* @create: 2019/11/06 15:19
*/
/*
题目:https://leetcode-cn.com/problems/valid-anagram/
类型:哈希等
难度:easy
*/
/*
输入: s = "anagram", t = "nagaram"
输出: true
输入: s = "rat", t = "car"
输出: false
*/
public class IsAnagram {
public static void main(String[] args) {
String s = "anagram";
String t = "nagaram";
System.out.println(isAnagram(s, t));
System.out.println(isAnagram2(s, t));
}
/**
* 普通字符串方法
* @param s
* @param t
* @return
*/
private static boolean isAnagram(String s, String t) {
int[] sCount = new int[26];
int[] tCount = new int[26];
for (char ch : s.toCharArray()) {
sCount[ch - 'a']++;
}
for (char c : t.toCharArray()) {
tCount[c - 'a']++;
}
for (int i = 0; i < 26; i++) {
if (sCount[i] != tCount[i]) {
return false;
}
}
return true;
}
/**
* 哈希
* @param s
* @param t
* @return
*/
private static boolean isAnagram2(String s, String t) {
HashMap<Character, Integer> map = new HashMap<>();
for (char c : s.toCharArray()) {
map.put(c, map.getOrDefault(c, 0) + 1);
}
for (char c : t.toCharArray()) {
Integer count = map.get(c);
if (count == null){
return false;
} else if (count > 1) {
map.put(c, count - 1);
} else {
map.remove(c);
}
}
return map.isEmpty();
}
}