-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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']-- ๋ฅผ ๊ฐ์ด ์งํํด์ฃผ์์ด๋ ๊ด์ฐฎ์์ ๊ฒ ๊ฐ์์! | ||
*/ |