|
| 1 | +/* |
| 2 | + Given two strings s and t, return true |
| 3 | + if t is an anagram of s, and false otherwise. |
| 4 | +
|
| 5 | + An anagram is a word or phrase formed by rearranging |
| 6 | + the letters of a different word or phrase, |
| 7 | + using all the original letters exactly once. |
| 8 | +
|
| 9 | + Input: s = "anagram", t = "nagaram" |
| 10 | + Output: true |
| 11 | +*/ |
| 12 | + |
| 13 | +#include <string> |
| 14 | +#include <unordered_map> |
| 15 | +using namespace std; |
| 16 | + |
| 17 | +// 첫 번째 풀이 --> 배열 두 개를 이용해서 직접 비교 |
| 18 | +#pragma region FirstIdea_TwoArrays |
| 19 | +namespace first_idea { |
| 20 | + |
| 21 | +class Solution { |
| 22 | +public: |
| 23 | + bool isAnagram(const string& s, const string& t) { |
| 24 | + int freq_s[26] = {}; |
| 25 | + int freq_t[26] = {}; |
| 26 | + |
| 27 | + if (s.length() != t.length()) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + |
| 31 | + for (size_t i = 0; i < s.length(); i++) { |
| 32 | + freq_s[s[i] - 'a']++; |
| 33 | + } |
| 34 | + |
| 35 | + for (size_t i = 0; i < t.length(); i++) { |
| 36 | + freq_t[t[i] - 'a']++; |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < 26; i++) { |
| 40 | + if (freq_s[i] != freq_t[i]) { |
| 41 | + return false; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + return true; |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +} // namespace first_idea |
| 50 | +#pragma endregion |
| 51 | + |
| 52 | +// 두 번째 풀이 --> 배열 하나를 사용해서 풀이 |
| 53 | +#pragma region FinalSolution_OneArray |
| 54 | +class Solution { |
| 55 | +public: |
| 56 | + bool isAnagram(const string& s, const string& t) { |
| 57 | + if (s.length() != t.length()) { |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + int freq[26] = {}; |
| 62 | + |
| 63 | + for (size_t i = 0; i < s.length(); i++) { |
| 64 | + freq[s[i] - 'a']++; |
| 65 | + freq[t[i] - 'a']--; |
| 66 | + } |
| 67 | + |
| 68 | + for (int count : freq) { |
| 69 | + if (count != 0) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + return true; |
| 75 | + } |
| 76 | +}; |
| 77 | +#pragma endregion |
| 78 | + |
| 79 | +// 세 번째 풀이 --> unordered_map 이용하기 |
| 80 | +#pragma region Alternative_UnorderedMap |
| 81 | +namespace unordered_map_idea { |
| 82 | + |
| 83 | +class Solution { |
| 84 | +public: |
| 85 | + bool isAnagram(const string& s, const string& t) { |
| 86 | + if (s.length() != t.length()) { |
| 87 | + return false; |
| 88 | + } |
| 89 | + |
| 90 | + unordered_map<char, int> freq; |
| 91 | + |
| 92 | + for (char ch : s) { |
| 93 | + freq[ch]++; |
| 94 | + } |
| 95 | + |
| 96 | + for (char ch : t) { |
| 97 | + freq[ch]--; |
| 98 | + } |
| 99 | + |
| 100 | + for (const auto& [ch, count] : freq) { |
| 101 | + if (count != 0) { |
| 102 | + return false; |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + return true; |
| 107 | + } |
| 108 | +}; |
| 109 | + |
| 110 | +} // namespace unordered_map_idea |
| 111 | +#pragma endregion |
0 commit comments