题解 | #牛群的配对#
牛群的配对
https://www.nowcoder.com/practice/c6677c8bd0d946e191051f19100c5cf5
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param s string字符串
# @return bool布尔型
#
class Solution:
def isValidPairing(self , s: str) -> bool:
# write code here
# 只有一个编号,肯定不能配对
if len(s) <= 1:
return False
stack = []
match = {'D': 'C', 'B': 'A'}
for c in s:
if c == 'A' or c == 'C':
stack.append(c)
else:
# 遇到B/D时,判断栈的情况
# 遇到B/D,但是栈空,说明匹配不上
if not stack:
return False
else:
if stack[-1] == match[c]:
stack.pop()
print("poped")
if stack:
return False
return True
就是括号匹配:按题目的意思AC相当于左括号,BD相当于右括号。
遇到AC就直接压栈,遇到BD,如果栈非空,说明少左括号,匹配失败;如果非空,则看栈顶元素是不是不匹配,匹配就成功,不匹配就不成功;循环结束后如果栈内还有元素,说明没匹配完,不成功