Skip to content

Commit 8fecf13

Browse files
committed
Valid Anagram
1 parent 09acb8f commit 8fecf13

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

โ€Žvalid-anagram/JisooPyo.kt

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
6+
/**
7+
* Leetcode
8+
* 242. Valid Anagram
9+
* Easy
10+
*/
11+
class ValidAnagram {
12+
/**
13+
* Runtime: 24 ms(Beats: 52.77 %)
14+
* Time Complexity: O(n)
15+
* - n: ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
16+
*
17+
* Memory: 38.32 MB(Beats: 31.34 %)
18+
* Space Complexity: O(1)
19+
* - ํ•ด์‹œ๋งต์˜ ํฌ๊ธฐ๊ฐ€ ์•ŒํŒŒ๋ฒณ ๊ฐœ์ˆ˜๋กœ ์ œํ•œ๋จ
20+
*/
21+
fun isAnagram(s: String, t: String): Boolean {
22+
if (s.length != t.length) return false
23+
val map = hashMapOf<Char, Int>()
24+
for (i in s.indices) {
25+
map[s[i]] = map.getOrDefault(s[i], 0) + 1
26+
}
27+
for (i in t.indices) {
28+
if (map[t[i]] == null || map[t[i]] == 0) {
29+
return false
30+
}
31+
map[t[i]] = map.get(t[i])!! - 1
32+
}
33+
return true
34+
}
35+
36+
/**
37+
* ํ•ด์‹œ๋งต ๋Œ€์‹  ๋ฐฐ์—ด์„ ์ด์šฉํ•œ ํ’€์ด
38+
* Runtime: 3 ms(Beats: 99.89 %)
39+
* Time Complexity: O(n)
40+
*
41+
* Memory: 37.25 MB(Beats: 80.30 %)
42+
* Space Complexity: O(1)
43+
*/
44+
fun isAnagram2(s: String, t: String): Boolean {
45+
if (s.length != t.length) return false
46+
val array = IntArray(26)
47+
for (i in s.indices) {
48+
array[s[i] - 'a']++
49+
}
50+
for (i in t.indices) {
51+
array[t[i] - 'a']--
52+
}
53+
for (num in array) {
54+
if (num != 0) {
55+
return false
56+
}
57+
}
58+
return true
59+
}
60+
61+
@Test
62+
fun test() {
63+
isAnagram("anagram", "nagaram") shouldBe true
64+
isAnagram("rat", "car") shouldBe false
65+
isAnagram2("anagram", "nagaram") shouldBe true
66+
isAnagram2("rat", "car") shouldBe false
67+
}
68+
}
69+
70+
/**
71+
* ๊ฐœ์„ ํ•  ์—ฌ์ง€ 1.
72+
* ์ฐพ์•„๋ณด๋‹ˆ IntArray.all ์ด๋ผ๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์–ด์„œ array.all { it == 0 } ์„ ์‚ฌ์šฉํ–ˆ์–ด๋„ ๊ดœ์ฐฎ์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
73+
* ๋ชจ๋“  ์š”์†Œ๊ฐ€ ์ฃผ์–ด์ง„ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š”์ง€ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค!
74+
*
75+
* ๊ฐœ์„ ํ•  ์—ฌ์ง€ 2.
76+
* s์™€ t์˜ ๋ฌธ์ž์—ด์ด ๊ฐ™์Œ์„ ๊ฒ€์‚ฌํ–ˆ์œผ๋ฏ€๋กœ ์ฒซ ๋ฒˆ์งธ for๋ฌธ์—์„œ array[t[i] - 'a']-- ๋ฅผ ๊ฐ™์ด ์ง„ํ–‰ํ•ด์ฃผ์—ˆ์–ด๋„ ๊ดœ์ฐฎ์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
77+
*/

0 commit comments

Comments
ย (0)