문제 : https://www.acmicpc.net/problem/14889
14889번: 스타트와 링크
예제 2의 경우에 (1, 3, 6), (2, 4, 5)로 팀을 나누면 되고, 예제 3의 경우에는 (1, 2, 4, 5), (3, 6, 7, 8)로 팀을 나누면 된다.
www.acmicpc.net
이 문제는 풀이는 쉬운데 써진 내용이 이해가 안됬었다.
밑에 예시를 보면 순서대로 1 넣고 2 넣고 3 넣고 4넣고 5 넣는다.
꺼낼 수 있는 것은 가장 최근에 넣은 것 즉 스택의 마지막 부분만 꺼낼 수 있다.
그래서 1~4넣고 가장 최근인 4꺼내고 다시 5넣고 꺼내고 3,2,1 꺼내고 이런식이다.
뭐 5안넣고 꺼내는 것도 가능하다. 예를들면 popped가 [4,3,2,1,5] 이면 이것도 true인 것이다.
Input: pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
Output: true
Explanation: We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -> 4,
push(5),
pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
코드
class Solution {
func validateStackSequences(_ pushed: [Int], _ popped: [Int]) -> Bool {
var result = [Int]()
var index = 0
for element in pushed {
result.append(element)
while !result.isEmpty && result.last == popped[index] {
result.removeLast()
index += 1
}
}
return result.count == 0
}
}
반응형
'알고리즘' 카테고리의 다른 글
[DFS] N과 M - baekjoon Swift (0) | 2021.08.23 |
---|---|
[투포인터] Container With Most Water - LeetCode Swift (2) | 2021.08.18 |
[Stack] 과제는 끝나지 않아! - Baekjoon 17952번 Swift (0) | 2021.08.13 |
[투포인터] Minimize Maximum Pair Sum in Array - LeetCode Swift (0) | 2021.08.11 |
[Heap] 우선순위 큐 - LeetCode Swift (0) | 2021.08.11 |