-
Notifications
You must be signed in to change notification settings - Fork 43
/
ValidAnagram.java
82 lines (65 loc) · 1.97 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package LeetCodeJava.String;
// https://leetcode.com/problems/valid-anagram/description/
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class ValidAnagram {
// V0
// IDEA : HASHMAP
public boolean isAnagram(String s, String t) {
if (s == null && t == null){
return true;
}
Map<String, Integer> sMap = new HashMap<>();
/** NOTE !!! split string via .split("") */
for (String x : s.split("")){
if (!sMap.containsKey(x)){
sMap.put(x, 1);
}
else{
sMap.put(x, sMap.get(x)+1);
}
}
for (String y : t.split("")){
if (!sMap.containsKey(y)){
return false;
}
sMap.put(y, sMap.get(y)-1);
if (sMap.get(y)==0){
sMap.remove(y);
}
}
if (sMap.keySet().size()!= 0){
return false;
}
return true;
}
// V1
// IDEA : ARRAY SORT
// https://leetcode.com/problems/valid-anagram/solutions/3687854/3-method-s-c-java-python-beginner-friendly/
public boolean isAnagram_1(String s, String t) {
char[] sChars = s.toCharArray();
char[] tChars = t.toCharArray();
Arrays.sort(sChars);
Arrays.sort(tChars);
return Arrays.equals(sChars, tChars);
}
// V2
// https://leetcode.com/problems/valid-anagram/solutions/3261552/easy-solutions-in-java-python-javascript-and-c-look-at-once/
public boolean isAnagram_2(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] freq = new int[26];
for (int i = 0; i < s.length(); i++) {
freq[s.charAt(i) - 'a']++;
freq[t.charAt(i) - 'a']--;
}
for (int i = 0; i < freq.length; i++) {
if (freq[i] != 0) {
return false;
}
}
return true;
}
}