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

brick·2023년 1월 29일
0

코테

목록 보기
17/53
func solution(_ s:String) -> Int {
    let s = Array(s)
    var test: String = ""
    var result: String = ""
    let words: [String: String] = ["zero": "0", "one": "1",
                                   "two": "2", "three": "3",
                                   "four": "4", "five": "5",
                                   "six": "6", "seven": "7",
                                   "eight": "8", "nine": "9"]
    
    for c in s {
        if c.isNumber {
            result.append(String(c))
            continue
        }
        
        test.append(String(c))
        if words.keys.contains(test) {
            result.append(words[test]!)
            test = ""
        }
    }
    

    return Int(result)!
}

func solution(_ s:String) -> Int {


    var s = s
        var answer = s.replacingOccurrences(of: "zero", with: "0")
            .replacingOccurrences(of: "one", with: "1")
            .replacingOccurrences(of: "two", with: "2")
            .replacingOccurrences(of: "three", with: "3")
            .replacingOccurrences(of: "four", with: "4")
            .replacingOccurrences(of: "five", with: "5")
            .replacingOccurrences(of: "six", with: "6")
            .replacingOccurrences(of: "seven", with: "7")
            .replacingOccurrences(of: "eight", with: "8")
            .replacingOccurrences(of: "nine", with: "9")

    return Int(answer)!
}

func solution(_ s:String) -> Int {
    let arr = ["zero","one","two","three","four","five","six","seven","eight","nine"]
    var str = s
    for i in 0..<arr.count {
        str = str.replacingOccurrences(of: arr[i], with: String(i))
    }
    return Int(str)!
}

0개의 댓글