https://leetcode.com/problems/valid-parentheses/
Valid Parentheses - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
기본적인 자료구조인 Stack을 이용하는 문제이다.
주어진 s문자열을 하나씩 탐색하는데,
( , { , [ 인경우에는 무조건 stack메모리에 추가해준다.
그외의경우에는 추가하지않는데,
이때, stack메모리의 마지막원소와 같은 bracket인지를 판별해야한다.
맞다면 마지막원소를 삭제하고, 그렇지않다면 이미 invalid 하다.
Array에는 유용한 프로퍼티가 있는데, last 를 이용하면 옵셔널타입으로 반환하기때문에,
이미 여기서 배열의 원소가없는경우에는 nil을 반환하기때문에
배열의원소가 없는 경우도 따로 조건처리하지않으면서 처리할수있다.
class Solution {
func isValid(_ s: String) -> Bool {
var stack = [String.Element]()
var isvalid = true
s.forEach{
switch $0 {
case "(", "[", "{":
stack.append($0)
case ")":
if stack.last != "(" {
isvalid = false
} else {
stack.removeLast()
}
case "]":
if stack.last != "[" {
isvalid = false
} else {
stack.removeLast()
}
case "}":
if stack.last != "{" {
isvalid = false
} else {
stack.removeLast()
}
default: print()
}
}
if !stack.isEmpty {
isvalid = false
}
return isvalid
}
}
'코딩테스트' 카테고리의 다른 글
백준 1508 - 레이스 - swift (0) | 2021.06.23 |
---|---|
백준 1459 - 걷기 - swift (0) | 2021.06.23 |
프로그래머스 - [1차] 비밀지도 - swift (0) | 2021.06.22 |
백준 15961 - 회전초밥 - swift (0) | 2021.06.22 |
LeetCode - 17. Letter Combinations of a Phone Number - swift (0) | 2021.06.17 |