- Date : 2021.07.25(일)
- Time : 25분
- Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
- An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
- 1 <= s.length <= 10^4
- s consists of parentheses only '()[]{}'.
- Input: s = "()[]{}"
- Output: true
def isValid(self, s: str) -> bool:
answerStack = []
answerDict = {')':'(',']':'[','}':'{'}
for i in s:
if i not in answerDict:
answerStack.append(i)
elif not answerStack or answerStack.pop() != answerDict[i] :
return False
if answerStack : return False
return True
: 먼저 딕셔너리 타입으로 짝을 지정해준다. 그리고 문자열을 하나씩 검사한다. if i not in asnwerDict
은 열리는 괄호인지 검사하는 것이다. 열리는 괄호라면 스택에 쌓는다. elif not answerStack or answerStack.pop() != answerDict[i]
은 닫히는 괄호인데 answerStack에 열리는 괄호가 없거나 있는데 마지막에 들어있는게 이 친구의 짝이 아닐 경우를 검사한다. 그러면 바로 False이다. for문을 다 돌았을 때 올바른 괄호들이였다면 배열이 비어있어야한다. 만약 그렇지 않다면 배열안에 값이 존재하므로 if문으로 마지막 검사를 진행해준다.