๋ฐ์ํ
๋ฌธ์ ๋งํฌ
https://www.acmicpc.net/problem/10866
๋ด๊ฐ ํผ ํ์ด
- ์ฝ๋ ๊ธธ์ด ์ ์์์ B๋ฅผ ๋ฐ์๋ค. ์ด๋ฅผ ์ค์ผ ์ ์๋ ๋ฐฉ๋ฒ, ๋ ํจ์จ์ ์ธ ์ฝ๋ฉ ๋ฐฉ๋ฒ์ด ๋ญ๊ฐ ์์๊น?
import Foundation
let n = Int(readLine()!)!
var answer: [String] = []
for _ in 0..<n {
var order = readLine()!.split(separator: " ").map { String($0) }
switch order[0] {
case "push_front":
answer.insert(order[1], at: 0)
case "push_back":
answer.append(order[1])
case "pop_front":
if answer.isEmpty {
print(-1)
}else{
print(answer.removeFirst())
}
case "pop_back":
if answer.isEmpty {
print(-1)
} else {
print(answer.removeLast())
}
case "size":
print(answer.count)
case "empty" :
if answer.isEmpty {
print(1)
}else {
print(0)
}
case "front" :
if answer.isEmpty {
print(-1)
} else {
print(answer[0])
}
default:
if answer.isEmpty {
print(-1)
} else{
print(answer.last!)
}
}
}
๋ค๋ฅธ ์ฌ๋ ํ์ด
- ๋ฐฑ์ค์ slow92๋์ ๊ณต๊ฐ๋ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํ์๋ค
- if๋ฌธ์ ์ฌ์ฉํ์ง ์๊ณ ์กฐ๊ฑด ? true:false ๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ์กฐ๊ธ ๋ ์งง์ ์ฝ๋ ๊ตฌํ์ด ๊ฐ๋ฅํ๋ค.
- ๋ฌธ์ ํผ์ฌ๋๋ค์ ์ฝ๋ ๊ธธ์ด๋ฅผ ๋ณด๋, ์ ๋ถ B๋ฅผ ๋ฐ์๊ธฐ ๋๋ฌธ์ ์ด๋ ํ๊ท ์ ์ธ ์์น์ธ๊ฒ ๊ฐ๋ค.
- ๊ทธ๋ฆฌ๊ณ ๋๋ถ๋ถ์์ฌ๋๋ค์ด switch case ํน์ func ์ผ๋ก ๋ฌธ์ ๋ฅผ ํ์๋ค.
var D:[Int] = []
for _ in 0..<Int(readLine()!)! {
let C = readLine()!.split{$0==" "}.map{String($0)}
let command = C.first!
var num = 0
if C.count > 1 {
num = Int(C.last!)!
}
switch command {
case "push_front": D.insert(num, at: 0)
case "push_back": D.append(num)
case "pop_front": print(D.isEmpty ? -1:D.removeFirst())
case "pop_back": print(D.isEmpty ? -1:D.removeLast())
case "size": print(D.count)
case "empty": print(D.isEmpty ? 1:0)
case "front": print(D.isEmpty ? -1:D.first!)
default: print(D.isEmpty ? -1:D.last!)
}
}
๋ฐ์ํ
'Algorithm > Baekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] (Swift) 1935๋ฒ - ํ์ ํ๊ธฐ์2 (0) | 2022.02.11 |
---|---|
[๋ฐฑ์ค] (Swift) 17413๋ฒ - ๋จ์ด๋ค์ง๊ธฐ2 (0) | 2022.02.07 |
[๋ฐฑ์ค] (Swift) 1158๋ฒ - ์์ธํธ์ค ๋ฌธ์ (0) | 2022.02.05 |
[๋ฐฑ์ค] (Swift) 10845๋ฒ - ํ (0) | 2022.02.04 |
[๋ฐฑ์ค] (Swift) 1406๋ฒ - ์๋ํฐ (2) | 2022.01.30 |