-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidAnagram_242.java
More file actions
48 lines (42 loc) · 1 KB
/
Copy pathValidAnagram_242.java
File metadata and controls
48 lines (42 loc) · 1 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
package com.leetcode.array;
import java.util.Arrays;
/**
* Created by charles on 2/27/17.
*/
public class ValidAnagram_242 {
/**
* naive solution O(nlgn)
*/
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] s1 = s.toCharArray();
char[] t1 = t.toCharArray();
Arrays.sort(s1);
Arrays.sort(t1);
return Arrays.equals(s1, t1);
}
/**
* Auxilury array as hash table
*/
public boolean isAnagramII(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] unicode = new int[256];
char[] s1 = s.toCharArray();
char[] t1 = t.toCharArray();
for (char c : s1) {
unicode[c]++;
}
for (char c : t1) {
if (unicode[c] > 0) {
unicode[c]--;
} else {
return false;
}
}
return true;
}
}