https://www.acmicpc.net/problem/4836
4836번: 춤
입력은 여러개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스는 한 줄로 이루어져 있으며, 창영이가 춘 춤이 주어진다. 각 춤은 1000스텝을 넘지 않는다. 각 스텝 알파벳 소문자로 이루어져
www.acmicpc.net
문자열 문제다. 쉽게 풀 수 있지만 문제 자체가 조금 번거롭기도 하고 꼼꼼히 보지 않으면 실수하기 쉽다.
풀이
배열에 담아 각 조건을 탐색하면 된다. 1번 조건의 "dip은 jiggle을 춘 다음이나 다다음, 또는 twirl을 추기 전에 출 수 있다." 부분에서 twril이 문장 이후 아무 데나 나오면 되는 것으로 착각했다. dip 바로 뒤에 twirl이 오는지만 확인하면 된다.
다른 조건들의 경우 배열의 contain 메소드를 사용하여 풀어내면 된다. 단 출력할 때의 문장 포맷을 잘 확인하고 출력하자. 제대로 확인 안 해서 틀린 부분을 찾아내느라 시간을 낭비했다. 문제를 꼼꼼히 읽었는지를 요하는 문제다.
정답 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
var ans = [String]() | |
while let dance = readLine(){ | |
if dance == ""{ break } | |
var step = dance.split(separator: " ").map{String($0)} | |
var errors = [Int]() | |
let length = step.count | |
if length < 3{ | |
errors.append(2) | |
}else{ | |
let ending = step[length-3...length-1].joined(separator: " ") | |
if ending != "clap stomp clap"{ | |
errors.append(2) | |
} | |
} | |
if step.contains("twirl") && !step.contains("hop"){ | |
errors.append(3) | |
} | |
if step[0] == "jiggle"{ | |
errors.append(4) | |
} | |
if !step.contains("dip"){ | |
errors.append(5) | |
} | |
for i in 0..<length{ | |
if step[i] == "dip"{ | |
var flag = false | |
for k in i-2..<i{ | |
if k<0 { continue } | |
if step[k] == "jiggle"{ flag = true} | |
} | |
if i+1 < length{ | |
if step[i+1] == "twirl"{ flag = true} | |
} | |
if !flag{ | |
step[i] = "DIP" | |
errors.append(1) | |
} | |
} | |
} | |
var res = String() | |
if errors.count == 0{ | |
res = "form ok: " + dance | |
}else if errors.count == 1{ | |
res = "form error " | |
res += "\(errors[0]): \(step.joined(separator: " "))" | |
}else{ | |
res = "form errors " | |
errors.sort(by: <) | |
for i in 0..<errors.count{ | |
res += "\(errors[i])" | |
if i < errors.count-2{ | |
res += ", " | |
}else{ | |
if i == errors.count-2{ | |
res += " and " | |
}else{ | |
res += ": \(step.joined(separator: " "))" | |
} | |
} | |
} | |
} | |
ans.append(res) | |
} | |
print(ans.joined(separator: "\n")) |

'Problem Solving > BOJ' 카테고리의 다른 글
[11444] 피보나치 수 6 (0) | 2023.02.08 |
---|---|
[17144] 미세먼지 안녕! (0) | 2023.02.07 |
[4485] 녹색 옷 입은 애가 젤다지? (0) | 2023.02.05 |
[3048] 개미 (0) | 2023.02.04 |
[14466] 소가 길을 건너간 이유 6 (0) | 2023.02.03 |