-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidAnagram.java
More file actions
82 lines (64 loc) · 1.98 KB
/
ValidAnagram.java
File metadata and controls
82 lines (64 loc) · 1.98 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
package other;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: Wenhang Chen
* @Description:给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
* <p>
* 示例 1:
* <p>
* 输入: s = "anagram", t = "nagaram"
* 输出: true
* 示例 2:
* <p>
* 输入: s = "rat", t = "car"
* 输出: false
* @Date: Created in 9:47 1/2/2020
* @Modified by:
*/
public class ValidAnagram {
public boolean isAnagram(String s, String t) {
if (s == null && t == null)
return true;
if (s == null || t == null || s.length() != t.length())
return false;
Map<Integer, Integer> hm = new HashMap<>();
for (int i = 0; i < s.length(); ) {
int key = s.codePointAt(i);
if (!hm.containsKey(key)) {
hm.put(key, 1);
} else {
hm.put(key, hm.get(key) + 1);
}
// 判断Unicode 代码点是否在附加级别字符范围内
if (Character.isSupplementaryCodePoint(key))
i += 2;
else
i++;
}
System.out.println(hm.toString());
for (int i = 0; i < t.length(); ) {
int key = t.codePointAt(i);
if (!hm.containsKey(key)) {
return false;
} else {
hm.put(key, hm.get(key) - 1);
}
// 判断Unicode 代码点是否在附加级别字符范围内
if (Character.isSupplementaryCodePoint(key))
i += 2;
else
i++;
}
for (Map.Entry entry : hm.entrySet()) {
//System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
if ((int) entry.getValue() != 0)
return false;
}
return true;
}
public static void main(String[] args) {
ValidAnagram va = new ValidAnagram();
va.isAnagram("rat", "car");
}
}