-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathValidAnagram.java
57 lines (55 loc) · 1.62 KB
/
ValidAnagram.java
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
package io.ziheng.hashtable.leetcode;
import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
/**
* LeetCode 242. Valid Anagram
* https://leetcode.com/problems/valid-anagram/
*/
public class ValidAnagram {
public boolean isAnagram(String s, String t) {
if (s == null || t == null || s.length() != t.length()) {
return false;
}
// return isAnagramSortWay(s, t);
return isAnagramHashWay(s, t);
}
public boolean isAnagramHashWay(String s, String t) {
char[] sCharArray = s.toCharArray();
char[] tCharArray = t.toCharArray();
Map<Character, Integer> map = new HashMap<>();
for (char c: sCharArray) {
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, 1 + map.get(c));
}
}
for (char c: tCharArray) {
if (!map.containsKey(c)) {
return false;
} else {
map.put(c, map.get(c) - 1);
}
}
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
if (entry.getValue() > 0) {
return false;
}
}
return true;
}
private boolean isAnagramSortWay(String s, String t) {
char[] sCharArray = s.toCharArray();
char[] tCharArray = t.toCharArray();
Arrays.sort(sCharArray);
Arrays.sort(tCharArray);
for (int i = 0; i < sCharArray.length; i++) {
if (sCharArray[i] != tCharArray[i]) {
return false;
}
}
return true;
}
}
/* EOF */