class My_Stack: def __init__(self, elements=[]): self._elements = list(elements) def is_empty(self): #return not self._elements return self._elements == [] def push(self, element): self._elements.append(element) def pop(self): if self.is_empty(): raise ValueError element = self._elements.pop() return element def func(input_str): st = My_Stack() for ch in input_str: if ch == "[" or ch == "(": st.push(ch) elif ch == "]": if st.is_empty(): print("false") return element = st.pop() if element != "[": print("false") return elif ch == ")": if st.is_empty(): print("false") return element = st.pop() if element != "(": print("false") return else: continue if not st.is_empty(): print("false") else: print("true") input_str = input() func(input_str)
"""" 括号匹配,借助栈后进先出的性质 """ if __name__ == "__main__": s = input().strip() ans = True flag = [] for c in s: if c == '[' or c == '(': flag.append(c) elif c == ']': if not flag or flag.pop() != '[': ans = False break elif c == ')': if not flag or flag.pop() != '(': ans = False break else: pass if flag: ans = False print("true" if ans else "false")