Skip to content

Commit 34a6520

Browse files
committed
solve Valid Anagram
1 parent 580d05f commit 34a6520

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import java.util.HashMap;
2+
3+
// link: https://leetcode.com/problems/valid-anagram/
4+
// difficulty: Easy
5+
class Solution1 {
6+
// Problem:
7+
// * return: is t an anagram of s
8+
public boolean isAnagram(String s, String t) {
9+
if(s.length() != t.length()) return false;
10+
11+
int n = s.length();
12+
13+
// Space Complexity: O(N)
14+
HashMap<Character, Integer> freqS = new HashMap<>();
15+
HashMap<Character, Integer> freqT = new HashMap<>();
16+
17+
// Time Complexity: O(N)
18+
for(int i = 0; i < n; i++) {
19+
char charS = s.charAt(i);
20+
freqS.put(charS, freqS.getOrDefault(charS, 0) + 1);
21+
22+
char charT = t.charAt(i);
23+
freqT.put(charT, freqT.getOrDefault(charT, 0) + 1);
24+
}
25+
26+
// Time Complexity: O(N)
27+
for(var entryS: freqS.entrySet()) {
28+
int cntT = freqT.getOrDefault(entryS.getKey(), 0);
29+
if(cntT != entryS.getValue()) return false;
30+
}
31+
32+
return true;
33+
}
34+
}
35+
36+
// Map ํ•˜๋‚˜๋งŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฐœ์„ ๋œ ๋ฐฉ์‹
37+
class Solution2 {
38+
// Problem:
39+
// * return: is t an anagram of s
40+
public boolean isAnagram(String s, String t) {
41+
if(s.length() != t.length()) return false;
42+
43+
int n = s.length();
44+
45+
// Space Complexity: O(N)
46+
HashMap<Character, Integer> freq = new HashMap<>();
47+
48+
// Time Complexity: O(N)
49+
for(int i = 0; i < n; i++) {
50+
char charS = s.charAt(i);
51+
freq.put(charS, freq.getOrDefault(charS, 0) + 1);
52+
53+
char charT = t.charAt(i);
54+
freq.put(charT, freq.getOrDefault(charT, 0) - 1);
55+
}
56+
57+
// Time Complexity: O(N)
58+
for(int count: freq.values()) {
59+
if(count != 0) return false;
60+
}
61+
62+
return true;
63+
}
64+
}

0 commit comments

Comments
ย (0)