Programming/Algorithm & Data Structure
[Swift] 프로그래머스 2021 카카오 채용연계형 인턴십 > 숫자 문자열과 영단어
guswlsdk
2022. 7. 5. 14:16
반응형
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
처음 정답으로 채점된 코드가 너무 지저분하다고 생각했다.
이 코드는 문자열 내에 숫자만 있을 때까지 문자열을 숫자로 바꾸는 코드이다.
func solution(_ s:String) -> Int {
let dict = ["zero","one","two","three","four","five","six","seven","eight","nine"]
var str = s
while str.range(of: "[a-z]", options: .regularExpression) != nil{
if let word = dict.first(where: {str.contains($0)}) {
str = str.replacingOccurrences(of: word, with: replacing(word: word))
}
}
return Int(str)!
}
func replacing(word: String) -> String{
switch word{
case "one": return "1"
case "two": return "2"
case "three": return "3"
case "four": return "4"
case "five": return "5"
case "six": return "6"
case "seven": return "7"
case "eight": return "8"
case "nine": return "9"
default: return "0"
}
}
아래에는 다른 사람의 코드를 보고 참고한 것이다.
func solution(_ s:String) -> Int {
let dict = ["zero" : "0","one" : "1", "two": "2","three" : "3", "four" : "4","five" : "5","six" : "6","seven" : "7","eight" : "8","nine" : "9"]
var str = s
for i in dict{
str = str.replacingOccurrences(of: i.key, with: i.value)
}
return Int(str)!
}
반응형