Skip to content

Commit

Permalink
valid anagram solution
Browse files Browse the repository at this point in the history
  • Loading branch information
5YoonCheol committed Dec 18, 2024
1 parent e0d7d23 commit 62f6663
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions valid-anagram/5YoonCheol.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import java.util.HashMap;

public class Solution {
public boolean isAnagram(String s, String t) {
//HashMap ์ž๋ฃŒ๊ตฌ์กฐ๋ฅผ ํ†ตํ•ด ์•„๋‚˜๊ทธ๋žจ ์—ฌ๋ถ€ ํŒ๋ณ„
//s,t ๋ฌธ์ž์—ด์—์„œ ๋ฌธ์ž์ธ ๊ฒƒ๋งŒ HashMap์— ๋„ฃ์–ด์ค€๋‹ค.
//์ด๋•Œ ์ค‘๋ณต์ธ ๊ฒฝ์šฐ value ๊ฐ’์„ 1์”ฉ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
//Character ํƒ€์ž…์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋งž์ง€ ์•Š์œผ๋ฉด false
//๋‘ ๊ฐœ์˜ Map์ด ์„œ๋กœ ๋™์ผํ•˜๋ฉด ์•„๋‚˜๊ทธ๋žจ์ด๋‹ค. -> true
//๊ทธ ์™ธ์˜ ๊ฒฝ์šฐ๋Š” Character์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋งž์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— false
HashMap<Character, Integer> sMap = new HashMap<>();
HashMap<Character, Integer> tMap = new HashMap<>();
for (Character c : s.toCharArray()) {
if (Character.isLetter(c)) {
sMap.put(c, sMap.getOrDefault(c, 0) + 1);
}
}

for (Character c : t.toCharArray()) {
if (Character.isLetter(c)) {
tMap.put(c, tMap.getOrDefault(c, 0) + 1);
}
}

if (sMap.size() != tMap.size()) return false;
else if (sMap.equals(tMap)) return true;
else return false;
}
}

0 comments on commit 62f6663

Please sign in to comment.