https://school.programmers.co.kr/learn/courses/30/lessons/159994
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
변수)
- cards1Index : cards1의 인덱스 (0부터 차례로 받을 것임 )
- cards2Index :cards2의 인덱스 (0부터 차례로 받을 것임 )
풀이
1. goal 문자열 배열을 반복문으로 접근해서 다음 조건문의 조건을 판단하여 맞으면 Index의 값을 증가함
2. 조건이 맞을 경우 Yes 반환 아닐 경우 반복문 도중에 No 반환
오답 (테스트 1 - 런타임 에러)
이유 : cardsIndex 를 증가시켜 cards배열의 크기보다 클경우에러 발생
for word in goal{
if cards1Index < cards1.count && cards1[cards1Index] == word {
cards1Index += 1
}
else if cards2Index < cards2.count && cards2[cards2Index] == word{
cards2Index += 1
}
else{
return "NO"
}
}
오답 (Out of Range)
이유 : cardsIndex 를 증가시켜 cards배열의 크기보다 클 경우에러 발생
다음과 같은 구문일 경우 cards1[cars1Index]를 먼저 판단하기 때문에 오류가 발생함
if cards1[cards1Index] == word && cards1Index < cards1.count{
cards1Index += 1
}
정답
import Foundation
func solution(_ cards1:[String], _ cards2:[String], _ goal:[String]) -> String {
var cards1Index = 0
var cards2Index = 0
for word in goal{
if cards1Index != cards1.count && cards1[cards1Index] == word {
if cards1Index < cards1.count-1{
cards1Index += 1
}
}
else if cards2Index != cards2.count && cards2[cards2Index] == word{
if cards2Index < cards2.count-1{
cards2Index += 1
}
}
else{
return "No"
}
}
return "Yes"
}
'Swift랑 친해지기 > programmers 풀기' 카테고리의 다른 글
[프로그래머스] 추억 점수 (Swift) (0) | 2023.04.25 |
---|---|
[프로그래머스] 달리기 경주 (Swift) <11,12,13 시간초과> (0) | 2023.04.23 |
[프로그래머스] 종이 자르기 (Swift) (0) | 2023.02.10 |
[프로그래머스] 둘만의 암호 (Swift) (0) | 2023.02.09 |
[프로그래머스] 진료 순서 정하기 (Swift) (0) | 2023.01.24 |