알고리즘

[프로그래머스][Swift] 숫자 문자열과 영단어

moving 2022. 8. 4. 15:13
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/81301?language=swift 

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

func solution(_ s: String) -> Int {
    let arr: [String] = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
    var str = ""
    var result: String = ""
    
    for (_, j) in s.enumerated() {
        if Int(String(j)) != nil {
            result += String(j)
        } else {
            str += String(j)
            if arr.contains(str) {
                let value = arr.firstIndex(of: str)!
                result += String(value)
                str = ""
            } else {
                continue
            }
        }
    }
    
    return Int(result)!
}

 

 

다른 사람의 풀이

func solution(_ s: String) -> Int {
    let dic = [
        "zero": "0", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"
    ]
    var s = s
    
    for i in dic {
        s =  s.replacingOccurrences(of: i.key, with: i.value)
    }

    return Int(s)!
}