#81301
๐ Question ?
https://school.programmers.co.kr/learn/courses/30/lessons/81301
class Solution {
fun solution(s: String): Int {
var answer: Int = 0
return answer
}
}
๐งฉ Thought Process
- ๊ฐ์ฅ ๋จผ์ string์์ string์ ์ผ๋ถ๋ถ(substring์ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ์ ๊ณต๋ถํด๋ณด์๋ค. ์ฐพ์๋ณด๋ subSequence(startIndex, endIndex) ๋ผ๋ ํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๋ฌธ์์ด์ ์ธ๋ฑ์ค๋ฅผ ์ง์ ํ์ฌ substring์ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ์ด ์์๋ค. endIndex๋ ํฌํจ๋์ง ์๋๋ค. ์ด๊ฑธ ์์ฉํด์ ๋ฌธ์ ๋ฅผ ํ์ด๋ด์ผ๊ฒ ๋ค.
- ๊ฐ์ฅ ๋จผ์ s์ character๋ฅผ ์ ์ํ์ผ๋ก ๋ฐ๊พธ์ด์ฃผ๊ณ (์์คํค ์ฝ๋ ์์ฉํด์ ํ์ดํ ๊ฑฐ์) ๋ฆฌ์คํธ์ ๋ฃ์ด์ฃผ์๋ค.
- while~do๋ฌธ์ผ๋ก ๋ฆฌ์คํธ ์ฌ์ด์ฆ ๋งํผ ๋๋ ค์ค. (size ํ๋กํผํฐ ์ฌ์ฉํ๊ธฐ)
- ๊ทธ ์์ when ๋ฌธ์ ๋๋ค์์ ์ด์ฉํ์ฌ ์์ฑํด์ฃผ๊ธฐ.
- ์๋ฌธ์ผ๋ก ์ ์ ์ซ์๊ฐ ์์ํ๋ ์ํ๋ฒณ์ z, o, t, f, s, e, n ์ด ์ผ๊ณฑ๊ฐ์ด๊ณ ์ด ์ํ๋ฒณ์ ๋์ํ๋ ์์คํค์ฝ๋๋ก ๊ฒฝ์ฐ๋ฅผ ๋๋์ด์ฃผ๊ธฐ
- ์์๋๋ ์ํ๋ฒณ์ด ์ค๋ณต๋๋ ๊ฒฝ์ฐ๋ ์ถ๊ฐ์ ์ผ๋ก ๊ฒฝ์ฐ ๋๋์ด์ฃผ๊ธฐ
class Solution {
fun solution(s: String): Int {
var answer: List<Int> = 0
var sArray = s.toCharArray()
var i = 0
do {
when(sArray[i]) {
in "z" -> (i += 4
answer.add(0))
in "o" -> (i += 3
answer.add(1))
in "t" -> (
when (sArray[i+1]) {
in "w" -> (i += 3
answer.add(2))
else -> (i += 5
answer.add(3))
})
in "f" -> (
when (sArray[i+1]) {
in "o" -> (i += 4
answer.add(4))
else -> (i += 4
answer.add(5))
})
in "s" -> (
when (sArray[i+1]) {
in "i" -> (i += 3
answer.add(6))
else -> (i += 5
answer.add(7))
})
in "e" -> (i += 5
answer.add(8))
in "n" -> (i += 4
answer.add(9))
else -> (answer.add(sArray[i].digitToInt())
i++
)
}
} while(i < sArray.size)
return answer.toInt()
}
}
์๋ง์ด์ง๋ง ๋ด๊ฐ ์์ฑํด๋ณธ ์ฝ๋.
๐ Answer
package Kakao_Internship_2021.์ซ์_๋ฌธ์์ด๊ณผ_์๋จ์ด
class Solution {
fun solution(s: String): Int {
val nums = arrayOf("zero", "one", "two", "three", "four", "five", "six", "seven","eight", "nine")
var str = s
for (i in 0 until nums.size) {
str = str.replace(nums[i], i.toString())
}
return str.toInt()
}
}
nums๋ผ๋ array์ ๋ชจ๋ ์๋ฅผ ์ ์ฅํ๊ณ ์ ์ฅ๋ ์์ ์ธ๋ฑ์ค๊ฐ ์ ํ์๋ ์์ ์ผ์นํจ์ ์ด์ฉํ์๋ค.
ํ์ด ๋ฏธ์ณค๋ค..
ํ์ด 2
fun main(args: Array<String>) {
println(solution("one4seveneight"))
println(solution("23four5six7"))
println(solution("2three45sixseven"))
println(solution("123"))
}
fun solution(s: String): Int {
val dicNumber: HashMap<String, String>
dicNumber = hashMapOf(
"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",
"zero" to "0"
)
var answer = ""
var stringNumber: String = ""
for (str in s) {
if (str.isDigit()) answer += str
else {
stringNumber += str
}
if (dicNumber.containsKey(stringNumber)) {
answer += dicNumber[stringNumber]
stringNumber = ""
}
}
return answer.toInt()
}
๋์ ๋๋ฆฌ๋ hashmapof ์ฌ์ฉํ ์ฝ๋.
๐ Result
๐ Comment
์ฑ๊ธฐ...