Nesting coding task - Learn to Code - Codility
의사 코드
입력값이 "("인 경우:
스택이 비어있으면 추가한다
스택이 비어있지 않으면
top이 ")"이면 return 0
아니라면 추가한다.
입력값이 ")"인 경우:
스택이 비어있으면 return 0
스택이 비어있지 않으면
top이 "("이면 popLast()
아니라면 return 0
stack의 길이가 0이라면 return 1, 아니라면 return 0
풀이
import Foundation
import Glibc
public func solution(_ S : inout String) -> Int {
var stack: [String] = []
for currentB in S {
if currentB == "(" {
if stack.isEmpty {
stack.append(String(currentB))
} else {
if stack.last! == ")" { return 0 }
else { stack.append(String(currentB)) }
}
} else { // ")"
if stack.isEmpty {
return 0
} else {
if stack.last! == "(" { _ = stack.popLast() }
else { return 0 }
}
}
}
return stack.count == 0 ? 1 : 0
}
'Dev > PS' 카테고리의 다른 글
| [Swift 알고리즘] Dominator - Codility (0) | 2024.03.01 |
|---|---|
| [Swift 알고리즘] stoneWall - Codility (0) | 2024.02.29 |
| [Swift 알고리즘] Fish - Codility (0) | 2024.02.29 |
| [Swift 알고리즘] Brackets - Codility (0) | 2024.02.15 |
| [Swift 알고리즘] NumberOfDiscIntersections - Codility (1) | 2024.02.09 |