|
| 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