알고리즘의 순서는 아래와 같다.
1. 입력값 s의 문자열 길이 만큼 반복문을 수행한다.
2. 현재 문자에 따라서 zero ~ nine까지 분기 처리를 한다.
3. 분기 처리 진행 후, 남은 문자만큼 건너 뛰어 1번으로 되 돌아간다.
다른 사람 풀이를 봤는데 굉장히 쉽게 해결한 것을 볼 수 있었다.
fun solution1(s: String) : Int = s.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")
.replace("zero","0").toInt()
문자열이 주어지니 replace 메소드를 이용해서 쉽게 해결한 모습이다.
정말 간단하지 않은가?
class Solution {
fun solution(s: String): Int {
val sb = StringBuilder()
var i = 0
while(i < s.length) {
val char = s[i]
sb.append(
when (char) {
'o' -> {
i += 3
1
}
't' ->{
when(s[i+1]){
'w' -> {
i+= 3
2
}
else ->{
i += 5
3
}
}
}
'f' -> {
when(s[i+1]){
'o' -> {
i += 4
4
}
else -> {
i += 4
5
}
}
}
's' ->{
when(s[i+1]){
'i' -> {
i +=3
6
}
else ->{
i += 5
7
}
}
}
'e' ->{
i += 5
8
}
'n' ->{
i +=4
9
}
'z' ->{
i +=4
0
}
else -> {
i++
char
}
}
)
}
return sb.toString().toInt()
}
}