Skip to content

Commit

Permalink
valid anagram
Browse files Browse the repository at this point in the history
  • Loading branch information
eunhwa99 committed Dec 15, 2024
1 parent 4c8241e commit 7d30552
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions valid-anagram/eunhwa99.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import java.util.HashMap;
import java.util.Map;

class Solution {
public boolean isAnagram(String s, String t) {

// s ์•ˆ์˜ ๋ฌธ์ž๋“ค์ด t ์—๋„ ๋™์ผํ•œ ํšŸ์ˆ˜๋กœ ๋“ฑ์žฅํ•˜๋Š” ์ง€ ํ™•์ธ
if (s.length() != t.length()) return false; // ๋‘ ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๊ฐ€ ๋‹ค๋ฅด๋‹ค๋ฉด ์•„๋‚˜๊ทธ๋žจ์ด ์•„๋‹ˆ๋‹ค.

// ๋ฌธ์ž๋ณ„ ํšŸ์ˆ˜ ์ €์žฅ map
Map<Character, Integer> sAlphabetCountMap = new HashMap<>();
for (char c : s.toCharArray()) { // ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
sAlphabetCountMap.put(c, sAlphabetCountMap.getOrDefault(c, 0) + 1);
}

for (char c : t.toCharArray()) { // ์‹œ๊ฐ„๋ณต์žก๋„: O(n)
if (!sAlphabetCountMap.containsKey(c)) return false; // s์— t๊ฐ€ ๊ฐ€์ง„ ๋ฌธ์ž์—ด์ด ์—†๋‹ค๋ฉด ์•„๋‚˜๊ทธ๋žจ์ด ์•„๋‹ˆ๋‹ค.

int count = sAlphabetCountMap.get(c) - 1;
if (count == 0) sAlphabetCountMap.remove(c);
else sAlphabetCountMap.put(c, count);
}

// ๋ชจ๋“  ๋ฌธ์ž๊ฐ€ ์ผ์น˜ํ•˜๋ฉด ํ•ด์‹œ๋งต์ด ๋น„์–ด ์žˆ์–ด์•ผ ํ•จ
return sAlphabetCountMap.isEmpty();
}
}

0 comments on commit 7d30552

Please sign in to comment.