在一行中输入一个字符串
,长度
,由可见字符组成。
如果字符串
中的括号部分能构成合法括号序列,则输出
;否则输出
。
abcd(])[efg
false
提取括号 `(`、`)`、`[`、`]` 后为 `(])[`,不是合法括号序列。
a[x(y)z]
true
提取括号后为 `[()]`,是合法括号序列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | s = list(input()) stack = [] ifs == '': print('true') else: fori in range(len(s)): ifs[i] == '('or s[i] == '[': stack.append(s[i]) ifs[i] == ')': iflen(stack) != 0 and stack[-1] == '(': stack.pop(-1) else: # print('false') stack.append(s[i]) # break ifs[i] == ']': iflen(stack) != 0and stack[-1] == '[': stack.pop(-1) else: # print('false') stack.append(s[i]) # break iflen(stack) == 0: print('true') else: print('false') |
s = input() stack = [] for i in s: if i=="("&nbs***bsp;i=="[": stack.append(i) elif i==")" : if stack!=[] and stack[-1]=="(": stack.pop() else: print("false") exit(0) elif i=="]": if stack!=[] and stack[-1]=="[": stack.pop() else: print("false") exit(0) print("true")
class Stack: def __init__(self) -> None: self.items = [] def push(self,x): self.items.append(x) def pop(self): if self.items: return self.items.pop() return None def is_empty(self): return len(self.items) == 0 def is_match(s): stack = Stack() for char in s: if char in "([": stack.push(char) elif char in ")]": if not stack: return False top = stack.pop() if (char == ")" and top != "(")&nbs***bsp;(char == ']' and top != "["): return False return stack.is_empty() s = input().strip() print(str(is_match(s)).lower())