Skip to content

Commit

Permalink
Valid Anagram
Browse files Browse the repository at this point in the history
  • Loading branch information
JisooPyo committed Dec 15, 2024
1 parent 09acb8f commit 8fecf13
Showing 1 changed file with 77 additions and 0 deletions.
77 changes: 77 additions & 0 deletions valid-anagram/JisooPyo.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package leetcode_study

import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test

/**
* Leetcode
* 242. Valid Anagram
* Easy
*/
class ValidAnagram {
/**
* Runtime: 24 ms(Beats: 52.77 %)
* Time Complexity: O(n)
* - n: ๋ฌธ์ž์—ด์˜ ๊ธธ์ด
*
* Memory: 38.32 MB(Beats: 31.34 %)
* Space Complexity: O(1)
* - ํ•ด์‹œ๋งต์˜ ํฌ๊ธฐ๊ฐ€ ์•ŒํŒŒ๋ฒณ ๊ฐœ์ˆ˜๋กœ ์ œํ•œ๋จ
*/
fun isAnagram(s: String, t: String): Boolean {
if (s.length != t.length) return false
val map = hashMapOf<Char, Int>()
for (i in s.indices) {
map[s[i]] = map.getOrDefault(s[i], 0) + 1
}
for (i in t.indices) {
if (map[t[i]] == null || map[t[i]] == 0) {
return false
}
map[t[i]] = map.get(t[i])!! - 1
}
return true
}

/**
* ํ•ด์‹œ๋งต ๋Œ€์‹  ๋ฐฐ์—ด์„ ์ด์šฉํ•œ ํ’€์ด
* Runtime: 3 ms(Beats: 99.89 %)
* Time Complexity: O(n)
*
* Memory: 37.25 MB(Beats: 80.30 %)
* Space Complexity: O(1)
*/
fun isAnagram2(s: String, t: String): Boolean {
if (s.length != t.length) return false
val array = IntArray(26)
for (i in s.indices) {
array[s[i] - 'a']++
}
for (i in t.indices) {
array[t[i] - 'a']--
}
for (num in array) {
if (num != 0) {
return false
}
}
return true
}

@Test
fun test() {
isAnagram("anagram", "nagaram") shouldBe true
isAnagram("rat", "car") shouldBe false
isAnagram2("anagram", "nagaram") shouldBe true
isAnagram2("rat", "car") shouldBe false
}
}

/**
* ๊ฐœ์„ ํ•  ์—ฌ์ง€ 1.
* ์ฐพ์•„๋ณด๋‹ˆ IntArray.all ์ด๋ผ๋Š” ๋ฉ”์„œ๋“œ๊ฐ€ ์žˆ์–ด์„œ array.all { it == 0 } ์„ ์‚ฌ์šฉํ–ˆ์–ด๋„ ๊ดœ์ฐฎ์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
* ๋ชจ๋“  ์š”์†Œ๊ฐ€ ์ฃผ์–ด์ง„ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š”์ง€ ๊ฒ€์‚ฌํ•˜๋Š” ๋ฉ”์„œ๋“œ๋ผ๊ณ  ํ•ฉ๋‹ˆ๋‹ค!
*
* ๊ฐœ์„ ํ•  ์—ฌ์ง€ 2.
* s์™€ t์˜ ๋ฌธ์ž์—ด์ด ๊ฐ™์Œ์„ ๊ฒ€์‚ฌํ–ˆ์œผ๋ฏ€๋กœ ์ฒซ ๋ฒˆ์งธ for๋ฌธ์—์„œ array[t[i] - 'a']-- ๋ฅผ ๊ฐ™์ด ์ง„ํ–‰ํ•ด์ฃผ์—ˆ์–ด๋„ ๊ดœ์ฐฎ์•˜์„ ๊ฒƒ ๊ฐ™์•„์š”!
*/

0 comments on commit 8fecf13

Please sign in to comment.