Skip to content
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
111 changes: 111 additions & 0 deletions valid-anagram/OstenHun.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
Given two strings s and t, return true
if t is an anagram of s, and false otherwise.

An anagram is a word or phrase formed by rearranging
the letters of a different word or phrase,
using all the original letters exactly once.

Input: s = "anagram", t = "nagaram"
Output: true
*/

#include <string>
#include <unordered_map>
using namespace std;

// 첫 번째 풀이 --> 배열 두 개를 이용해서 직접 비교
#pragma region FirstIdea_TwoArrays
namespace first_idea {

class Solution {
public:
bool isAnagram(const string& s, const string& t) {
int freq_s[26] = {};
int freq_t[26] = {};

if (s.length() != t.length()) {
return false;
}

for (size_t i = 0; i < s.length(); i++) {
freq_s[s[i] - 'a']++;
}

for (size_t i = 0; i < t.length(); i++) {
freq_t[t[i] - 'a']++;
}

for (int i = 0; i < 26; i++) {
if (freq_s[i] != freq_t[i]) {
return false;
}
}

return true;
}
};

} // namespace first_idea
#pragma endregion

// 두 번째 풀이 --> 배열 하나를 사용해서 풀이
#pragma region FinalSolution_OneArray
class Solution {
public:
bool isAnagram(const string& s, const string& t) {
if (s.length() != t.length()) {
return false;
}

int freq[26] = {};

for (size_t i = 0; i < s.length(); i++) {
freq[s[i] - 'a']++;
freq[t[i] - 'a']--;
}

for (int count : freq) {
if (count != 0) {
return false;
}
}

return true;
}
};
#pragma endregion

// 세 번째 풀이 --> unordered_map 이용하기
#pragma region Alternative_UnorderedMap
namespace unordered_map_idea {

class Solution {
public:
bool isAnagram(const string& s, const string& t) {
if (s.length() != t.length()) {
return false;
}

unordered_map<char, int> freq;

for (char ch : s) {
freq[ch]++;
}

for (char ch : t) {
freq[ch]--;
}

for (const auto& [ch, count] : freq) {
if (count != 0) {
return false;
}
}

return true;
}
};

} // namespace unordered_map_idea
#pragma endregion
Loading