Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[choidabom] Week 2 #715

Merged
merged 4 commits into from
Dec 22, 2024
Merged
Changes from 2 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
56 changes: 56 additions & 0 deletions valid-anagram/choidabom.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/**
* Runtime: 24ms, Memory: 55.95MB
*
* 접근: 문자들끼리 anagram 관계인 경우, 정렬했을 때 같은 값을 가지기에 각 문자열 정렬 후 비교.
*/

function isAnagram(s: string, t: string): boolean {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이 풀이의 복잡도도 분석해서, 위아래의 풀이의 장단점을 비교해 주신다면 좀더 풍성한 논의가 오고갈 수 있을 것 같아요!

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

function sortedString(s: string): string {
return s.split("").sort().join("");
}

/**
* Runtime: 19ms, Memory: 55.02MB
*
* 접근: 문자들끼리 anagram 관계인 경우, 각 문자들의 count가 동일할 것이기에 Map 자료구조를 이용해서 합/차 계산
* Time Complexity: O(N)
* Space Complexity: O(N)
*/
function isAnagram(s: string, t: string): boolean {
if (s.length !== t.length) {
return false;
}

let map = new Map<string, number>();
for (const char of s) {
if (map.has(char)) {
map.set(char, map.get(char)! + 1);
} else {
map.set(char, 1);
}
}

for (const char of t) {
if (map.has(char)) {
map.set(char, map.get(char)! - 1);
} else {
return false;
}
}

for (const value of map.values()) {
if (value !== 0) {
return false;
}
}

return true;
}

console.log(isAnagram("anagram", "nagaram"));
Loading