Skip to content

Commit 119a30e

Browse files
committed
add: Valid Anagram solution
1 parent dfab7de commit 119a30e

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

โ€Žvalid-anagram/yoouyeon.tsโ€Ž

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* [Idea]
3+
* s์—์„œ ๊ฐ ๋ฌธ์ž๊ฐ€ ๋ช‡๋ฒˆ ๋“ฑ์žฅํ•˜๋Š”์ง€ ์„ธ์–ด์ค€๋‹ค. (charCount)
4+
* t์—์„œ ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๋ฉด์„œ charCount์˜ ๊ฐ’์„ ๊ฐ์†Œ์‹œํ‚จ๋‹ค.
5+
* ๋ฌธ์ž์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋ถ€์กฑํ•˜๊ฑฐ๋‚˜ ๋‚จ๋Š”๋‹ค๋ฉด ์• ๋„ˆ๊ทธ๋žจ์ด ์•„๋‹ˆ๋‹ค.
6+
*
7+
* [Time Complexity]
8+
* O(n + n + k) => O(n) (n: s์™€ t์˜ ๊ธธ์ด, k: ๋‘ ๋ฌธ์ž์—ด์— ๋“ฑ์žฅํ•˜๋Š” ๊ณ ์œ  ๋ฌธ์ž ์ˆ˜)
9+
*
10+
* [Space Complexity]
11+
* O(n)
12+
* ๋ฌธ์ž ๋“ฑ์žฅ ํšŸ์ˆ˜๋ฅผ ์„ธ์–ด์ฃผ๋Š” charCount์— ํ•„์š”ํ•œ ๊ณต๊ฐ„
13+
*/
14+
function isAnagram(s: string, t: string): boolean {
15+
const charCount: Record<string, number> = {};
16+
for (const char of s) {
17+
charCount[char] = (charCount[char] ?? 0) + 1;
18+
}
19+
20+
for (const char of t) {
21+
if (charCount[char] === undefined || charCount[char] === 0) {
22+
return false;
23+
}
24+
charCount[char]--;
25+
}
26+
27+
return Object.values(charCount).every((count) => count === 0);
28+
}

0 commit comments

Comments
ย (0)