Skip to content

Commit 7d30552

Browse files
committed
valid anagram
1 parent 4c8241e commit 7d30552

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
class Solution {
5+
public boolean isAnagram(String s, String t) {
6+
7+
// s ์•ˆ์˜ ๋ฌธ์ž๋“ค์ด t ์—๋„ ๋™์ผํ•œ ํšŸ์ˆ˜๋กœ ๋“ฑ์žฅํ•˜๋Š” ์ง€ ํ™•์ธ
8+
if (s.length() != t.length()) return false; // ๋‘ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด ์•„๋‚˜๊ทธ๋žจ์ด ์•„๋‹ˆ๋‹ค.
9+
10+
// ๋ฌธ์ž๋ณ„ ํšŸ์ˆ˜ ์ €์žฅ map
11+
Map<Character, Integer> sAlphabetCountMap = new HashMap<>();
12+
for (char c : s.toCharArray()) { // ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
13+
sAlphabetCountMap.put(c, sAlphabetCountMap.getOrDefault(c, 0) + 1);
14+
}
15+
16+
for (char c : t.toCharArray()) { // ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
17+
if (!sAlphabetCountMap.containsKey(c)) return false; // s์— t๊ฐ€ ๊ฐ€์ง„ ๋ฌธ์ž์—ด์ด ์—†๋‹ค๋ฉด ์•„๋‚˜๊ทธ๋žจ์ด ์•„๋‹ˆ๋‹ค.
18+
19+
int count = sAlphabetCountMap.get(c) - 1;
20+
if (count == 0) sAlphabetCountMap.remove(c);
21+
else sAlphabetCountMap.put(c, count);
22+
}
23+
24+
// ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•˜๋ฉด ํ•ด์‹œ๋งต์ด ๋น„์–ด ์žˆ์–ด์•ผ ํ•จ
25+
return sAlphabetCountMap.isEmpty();
26+
}
27+
}

0 commit comments

Comments
ย (0)