-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlce_p0242_valid_anagram.java
More file actions
87 lines (66 loc) · 1.76 KB
/
lce_p0242_valid_anagram.java
File metadata and controls
87 lines (66 loc) · 1.76 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
LCE 242. Valid Anagram
Given two strings s and t, return true if t is an anagram of s, and false otherwise.
Constraints:
- 1 <= s.length, t.length <= 5 * 10^4
- s and t consist of lowercase English letters.
Topics:
- Hash Table
- String
- Sorting
*/
import java.util.Arrays;
class Solution {
// Time Complexity: O(n) - 2 ms -> 97.88%
// Space Complexity: O(1) - 43.0 MB -> 76.06%
public boolean isAnagram(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] freqS = new int[26];
int[] freqT = new int[26];
for (char ch : s.toCharArray()) {
freqS[ch - 'a']++;
}
for (char ch : t.toCharArray()) {
freqT[ch - 'a']++;
}
return Arrays.equals(freqS, freqT);
}
// Time Complexity: O(n) - 6 ms -> 44.40%
// Space Complexity: O(1) - 42.9 MB -> 85.96%
public boolean isAnagramAlt1(String s, String t) {
if (s.length() != t.length()) {
return false;
}
int[] freqArr = new int[26];
for (int i = 0; i < s.length(); i++) {
freqArr[s.charAt(i) - 'a']++;
freqArr[t.charAt(i) - 'a']--;
}
for (int freq : freqArr) {
if (freq != 0) {
return false;
}
}
return true;
}
// Time Complexity: O(n log n + m log m) - 4 ms -> 76.24%
// Space Complexity: O(1) - 44.9 MB -> 13.69%
public boolean isAnagramAlt2(String s, String t) {
if (s.length() != t.length()) {
return false;
}
char[] charS = s.toCharArray();
char[] charT = t.toCharArray();
Arrays.sort(charS);
Arrays.sort(charT);
return Arrays.equals(charS, charT);
}
}
/*
methods:
1. frequency array (compares array contents)
2. frequency array (checks for equilibrium)
3. sorting (sort then compare array contents)
*/