|
| 1 | +/** |
| 2 | + ํ์ด : |
| 3 | + Map์ ์ด์ฉํ์ฌ ๋ ๋ฌธ์์ด์ ๋ฌธ์๋ค์ ํ์๋ฅผ ์ ์ฅํ๊ณ ๋น๊ตํ๋ ๊ฒ |
| 4 | +
|
| 5 | + ๋ณต์ก๋ ๊ณ์ฐ : |
| 6 | + ๋ฌธ์์ ๊ธธ์ด -> N |
| 7 | + ์๊ฐ ๋ณต์ก๋ : O(N) |
| 8 | + ๊ณต๊ฐ ๋ณต์ก๋ : O(N) |
| 9 | +*/ |
| 10 | +class Solution1 { |
| 11 | + public boolean isAnagram(String s, String t) { |
| 12 | + Map<Character, Integer> targetMap = new HashMap<>(); |
| 13 | + Map<Character, Integer> diffMap = new HashMap<>(); |
| 14 | + calculate(s, targetMap); |
| 15 | + calculate(t, diffMap); |
| 16 | + if(isSameMap(targetMap, diffMap)) { |
| 17 | + return true; |
| 18 | + } else { |
| 19 | + return false; |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + public void calculate(String s, Map<Character, Integer> map) { |
| 24 | + for(int i = 0; i < s.length(); i++) { |
| 25 | + char ch = s.charAt(i); |
| 26 | + map.put(ch, map.getOrDefault(ch, 0) + 1); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + public boolean isSameMap(Map<Character, Integer> map, Map<Character, Integer> targetMap) { |
| 31 | + if(map.size() != targetMap.size()) { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + for(Character key : map.keySet()) { |
| 36 | + if(!map.get(key).equals(targetMap.get(key))) { |
| 37 | + return false; |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + return true; |
| 42 | + } |
| 43 | + |
| 44 | +} |
| 45 | +/** |
| 46 | + ํ์ด : |
| 47 | + ์ํ๋ฒณ ๋ฌธ์ ํ์๋ฅผ ์ ์ฅํ๋ ๋ฐฐ์ด์ ๋ง๋ค๊ณ , ๋ ๋ฌธ์์ด์ ๋ฌธ์๋ฅด ์ํํ๋ฉด์ ํฉ์ ๊ตฌํจ. |
| 48 | +
|
| 49 | + ๋ณต์ก๋ ๊ณ์ฐ : |
| 50 | + ๋ฌธ์์ ๊ธธ์ด -> N |
| 51 | + ์๊ฐ ๋ณต์ก๋ : O(N) |
| 52 | + ๊ณต๊ฐ ๋ณต์ก๋ : O(1) |
| 53 | +*/ |
| 54 | + |
| 55 | +class Solution2 { |
| 56 | + public boolean isAnagram(String s, String t) { |
| 57 | + |
| 58 | + if(s.length() != t.length()) { |
| 59 | + return false; |
| 60 | + } |
| 61 | + |
| 62 | + int[] alphbet = new int[26]; |
| 63 | + |
| 64 | + for(int i = 0; i< s.length(); i++) { |
| 65 | + int idx = s.charAt(i) - 'a'; |
| 66 | + alphbet[s.charAt(i) - 'a']++; |
| 67 | + |
| 68 | + int idx2 = t.charAt(i) - 'a'; |
| 69 | + alphbet[idx2]--; |
| 70 | + } |
| 71 | + |
| 72 | + for(int i = 0; i < 26; i++) { |
| 73 | + if(alphbet[i] != 0) { |
| 74 | + return false; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return true; |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments