Valid parenthesis¶

Idea is¶
1) Use a stack to store open parenthesis, brackets and curly brackets¶
2) Pop most recent element each time a close parenthesis, bracket or curly bracket is found¶
a) if the stack is empty and pop can't be perform, return False¶
b) it they not pair, return False¶
c) If they pair, go to next character¶
3) At the end if the stack is empty (no remaining open parenthesis, brackets or curly brackets)¶
In [ ]:
from collections import deque

def isValid(s: str) -> bool:
    q, d = deque(), {'(': ')', '[': ']', '{': '}'}
    for c in s:
        if c in ['(', '[', '{']:
            q.append(c)
        else:
            if (not q) or d[q.pop()] != c:
                return(False)
    return(not q) # check that q is empty ie that there is no open parenthis left