티스토리 뷰
문제
https://www.acmicpc.net/problem/10866
10866번: 덱
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
풀이
deque이라는 자료구조를 맛보기 위해 풀어보았다.
queue와 마찬가지로 두 개의 배열로 구현할 수 있다. deque은 양쪽 모두 push와 pop이 가능하기 때문에 queue를 구현했던 코드에서 살짝만 추가해주면 된다.
이전에 queue에서 pop을 구현할때 right가 비어있으면 left를 뒤집어서 넣은 뒤에 removeLast()로 구현했었는데, deque에서도 마찬가지로 구현하면되지만 right와 left만 바꿔주면 될 것이다.
right.reversed() + left가 원래의 형태라는걸 생각하면 쉬움.
import Foundation
let n = Int(readLine()!)!
var left: [String] = []
var right: [String] = []
for _ in 0..<n {
let input = readLine()!.split(separator: " ").map { String($0) }
if input[0] == "push_front" {
right.append(input[1])
} else if input[0] == "push_back" {
left.append(input[1])
} else if input[0] == "pop_front" {
if left.isEmpty && right.isEmpty {
print(-1)
} else {
if right.isEmpty {
right = left.reversed()
left.removeAll()
}
print(right.removeLast())
}
} else if input[0] == "pop_back" {
if left.isEmpty && right.isEmpty {
print(-1)
} else {
if left.isEmpty {
left = right.reversed()
right.removeAll()
}
print(left.removeLast())
}
} else if input[0] == "size" {
print(left.count + right.count)
} else if input[0] == "empty" {
if left.isEmpty && right.isEmpty {
print(1)
} else {
print(0)
}
} else if input[0] == "front" {
if left.isEmpty && right.isEmpty {
print(-1)
} else {
right.isEmpty ? print(left[0]) : print(right.last!)
}
} else {
if left.isEmpty && right.isEmpty {
print(-1)
} else {
left.isEmpty ? print(right[0]) : print(left.last!)
}
}
}
_____________________________________________________________________________________________________
애플에서 오픈소스로 만든 collections를 이용하고싶음.
'PS' 카테고리의 다른 글
[Swift] 백준_좋은 친구(3078) (0) | 2023.01.10 |
---|---|
[Swift] 백준_AC(5430) (0) | 2023.01.09 |
[Swift] 백준_Router(15828) (0) | 2023.01.08 |
[Swift] 백준_오아시스 재결합 (0) | 2023.01.07 |
[Swift] 백준_트럭(13335) (0) | 2023.01.06 |
댓글
최근에 올라온 글
- Total
- Today
- Yesterday