๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/81301?language=kotlin
์์
https://school.programmers.co.kr/learn/courses/30/lessons/81301?language=kotlin
ํ์ด
๋จผ์ ๋ฌธ์์ด์ ํด๋นํ๋ ์ซ์์ ๋์ํ๋ map์ ์์ฑํฉ๋๋ค.
์ดํ ์ฃผ์ด์ง ๋ฌธ์์ด์ ํ๋์ฉ ํ์ธํ๋ฉด์ ์๋จ์ด๋ StringBuilder์ ์ ์ฅํ๊ณ ์ซ์์ผ ๊ฒฝ์ฐ์๋ answer ๊ฐ์ ๋ํ๋ ๋ฐฉ์์ผ๋ก ๊ตฌํํ์์ต๋๋ค.
๋ฌธ์์ด ์๋จ์ด๊ฐ ์ฐ์์ ์ผ๋ก ๋์ฌ ์ ์๊ธฐ ๋๋ฌธ์ StringBuilder์ ์ ์ฅํ ํ์ map์ StringBuilder์ ์ ์ฅ๋ ๊ฐ๊ณผ ์ผ์นํ๋ ๊ฐ์ด ์๋์ง ํ์ธํ์ฌ ์์ ๊ฒฝ์ฐ์ answer์ ๋ํ ํ StringBuilder๋ฅผ clear ํฉ๋๋ค.
class NumberString{
fun solution(s: String): Int {
var answer: String = ""
val map = mapOf(
"zero" to 0,
"one" to 1,
"two" to 2,
"three" to 3,
"four" to 4,
"five" to 5,
"six" to 6,
"seven" to 7,
"eight" to 8,
"nine" to 9
)
val str = StringBuilder()
s.forEach{ ch ->
if(ch.isLetter()){
str.append(ch)
if(map.contains(str.toString())){
answer = answer+map[str.toString()]!!
str.clear()
}
}else{
answer+=ch
}
}
if(str.isNotEmpty()){
if(str.isNotEmpty()){
answer = answer + map[str.toString()]!!
}
}
return answer.toInt()
}
}
์์ฒ๋ผ ํ์ด๋ ๋ฌด๋ฐฉํ์ง๋ง ํจ์ฌ ๊ฐ๋จํ ํ์ด๊ฐ ์กด์ฌํฉ๋๋ค.
String ํด๋์ค์ replace ๋ฉ์๋๋ง ์๊ณ ์๋ค๋ฉด ์ฒด์ด๋ ๊ธฐ๋ฒ์ ํ์ฉํ์ฌ ํ ์ค๋ก ํ ์ ์์ต๋๋ค.
class NumberString{
fun solution2(s: String): Int = s.replace("zero", "0")
.replace("one","1")
.replace("two","2")
.replace("three", "3")
.replace("four", "4")
.replace("five","5")
.replace("six", "6")
.replace("seven","7")
.replace("eight","8")
.replace("nine", "9")
.toInt()
}
์ฐธ๊ณ
StringBuilder - Kotlin Programming Language
kotlinlang.org
Kotlin - String Replace - Examples
The basic String Replace method in Kotlin is String.replace(oldValue, newValue). ignoreCase is an optional argument, that could be sent as third argument to the replace() method. In this tutorial, we shall go through examples where we shall replace an old
www.tutorialkart.com
isLetter - Kotlin Programming Language
kotlinlang.org