728x90
https://school.programmers.co.kr/learn/courses/30/lessons/81301
문제 설명
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다.
다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.
- 1478 → "one4seveneight"
- 234567 → "23four5six7"
- 10203 → "1zerotwozero3"
이렇게 숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s
가 매개변수로 주어집니다. s
가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.
참고로 각 숫자에 대응되는 영단어는 다음 표와 같습니다.
숫자 | 영단어 |
---|---|
0 | zero |
1 | one |
2 | two |
3 | three |
4 | four |
5 | five |
6 | six |
7 | seven |
8 | eight |
9 | nine |
제한사항
- 1 ≤
s
의 길이 ≤ 50 s
가 "zero" 또는 "0"으로 시작하는 경우는 주어지지 않습니다.- return 값이 1 이상 2,000,000,000 이하의 정수가 되는 올바른 입력만
s
로 주어집니다.
입출력 예
s | result |
---|---|
"one4seveneight" |
1478 |
"23four5six7" |
234567 |
"2three45sixseven" |
234567 |
"123" |
123 |
입출력 예 설명
입출력 예 #1
- 문제 예시와 같습니다.
입출력 예 #2
- 문제 예시와 같습니다.
입출력 예 #3
- "three"는 3, "six"는 6, "seven"은 7에 대응되기 때문에 정답은 입출력 예 #2와 같은 234567이 됩니다.
- 입출력 예 #2와 #3과 같이 같은 정답을 가리키는 문자열이 여러 가지가 나올 수 있습니다.
입출력 예 #4
s
에는 영단어로 바뀐 부분이 없습니다.
제한시간 안내
- 정확성 테스트 : 10초
풀이
replacingOccurrences(of:,with:) 을 이용하여 문자인 숫자를 교체
코드
func solution(_ s:String) -> Int {
var strNum = s
if s.contains("zero") {
strNum = strNum.replacingOccurrences(of: "zero", with: "0")
}
if s.contains("one") {
strNum = strNum.replacingOccurrences(of: "one", with: "1")
}
if s.contains("two") {
strNum = strNum.replacingOccurrences(of: "two", with: "2")
}
if s.contains("three") {
strNum = strNum.replacingOccurrences(of: "three", with: "3")
}
if s.contains("four") {
strNum = strNum.replacingOccurrences(of: "four", with: "4")
}
if s.contains("five") {
strNum = strNum.replacingOccurrences(of: "five", with: "5")
}
if s.contains("six") {
strNum = strNum.replacingOccurrences(of: "six", with: "6")
}
if s.contains("seven") {
strNum = strNum.replacingOccurrences(of: "seven", with: "7")
}
if s.contains("eight") {
strNum = strNum.replacingOccurrences(of: "eight", with: "8")
}
if s.contains("nine") {
strNum = strNum.replacingOccurrences(of: "nine", with: "9")
}
return Int(strNum)!
}
다른 사람 풀이
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)!
}
728x90
'알고리즘 > 프로그래머스' 카테고리의 다른 글
프로그래머스: 월간 코드 챌린지 시즌2 - 음양 더하기 (0) | 2022.07.28 |
---|---|
프로그래머스: 2019 카카오 개발자 겨울 인턴십 - 크레인 인형뽑기 게임 (0) | 2022.07.28 |
프로그래머스: 없는 숫자 더하기 (0) | 2022.07.26 |
프로그래머스: 2021 카카오 블라인드 - 신규 아이디 추천 (0) | 2022.07.22 |
프로그래머스: 2018 카카오 블라인드 - 1차 다트게임 (0) | 2022.07.19 |
댓글