-
Notifications
You must be signed in to change notification settings - Fork 1
/
LeetCode-242-Valid-Anagram.java
49 lines (37 loc) · 1.26 KB
/
LeetCode-242-Valid-Anagram.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
/*
LeetCode: https://leetcode.com/problems/valid-anagram/
Other: http://www.cnblogs.com/grandyang/p/4694988.html
https://leetcode.com/discuss/49399/accepted-java-o-n-solution-in-5-lines
Analysis:
must check if s and t's length is same
1.Sort
2.Using an Array as map
*/
public class Solution {
// 1.Sort
// public boolean isAnagram(String s, String t) {
// if(s == null || t == null || s.length() != t.length()) return false;
// char[] sarr = s.toCharArray();
// char[] tarr = t.toCharArray();
// java.util.Arrays.sort(sarr);
// java.util.Arrays.sort(tarr);
// return java.util.Arrays.equals(sarr, tarr);
// }
// 2.Using an array as a map
public boolean isAnagram(String s, String t) {
if(s == null || t == null || s.length() != t.length()) return false;
int[] map = new int['z' - 'a' + 1];
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
map[ch - 'a']++;
}
for(int i = 0; i < t.length(); i++){
char ch = t.charAt(i);
map[ch - 'a']--;
}
for(int i : map){
if(i != 0) return false;
}
return true;
}
}