개인 공부/프로그래머스

[프로그래머스] 영어가 싫어요 swift

임구마🍠 2024. 6. 14. 18:35


 

나의 풀이

import Foundation

func solution(_ numbers:String) -> Int64 {
    let alpha = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    var strNum = ""
    var result = ""
    
    for i in numbers {
        strNum += String(i)
        if alpha.contains(strNum), let index = alpha.firstIndex(of: strNum) {
            strNum = ""
            result += String(index)
        } else {
            continue
        }
    }

    return Int64(result)!
}

- numbers 문자열에서 문자를 하나씩 가져와서 strNum 더해주어 alpha 배열에 해당 문자열이 있을 경우, 인덱스 추출

- 인덱스 추출 후 strNum 초기화 및 결과값에 인덱스 값 문자열로 변환하여 추가 (인덱스 값이 결국 영어 표기 -> 숫자 표기 값)

- alpha 문자열에 해당되지 않는 문자열일 경우엔 continue

 

 

다른 사람의 풀이