You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用NumPy数组实现括号匹配?解决无pop()方法的问题

括号序列匹配:用NumPy替代列表实现栈功能

我正在尝试实现括号序列匹配功能,参考HackerRank的Balanced Brackets题目。希望使用NumPy数组替代列表,但NumPy没有pop()函数,不知道如何从NumPy数组中弹出元素并存储到其他列表/数组中。

我的尝试代码

import numpy as np
t = int(input("Count: "))
while t:
    ar = np.array('')
    s = input()
    for i in s:
        if i == '(':
            np.append(['('])
        elif i == '[':
            np.append(['['])
        elif i == '{':
            np.append(['{'])
        elif i == ')':
            k = np.pop(ar)
            if k != '(':
                np.append(['k'])
                break
        elif i == ']':
            k = np.pop(ar)
            if k != '[':
                np.append(['k'])
                break
        elif i == '}':
            k = np.pop(ar)
            if k != '{':
                np.append(['k'])
                break
    
    if len(ar) == 0 or ar[len(ar)-1] != '':
        print('NO')
    else:
        print('YES')
    t-=1

我已尝试将括号字符串存入数组,但不知如何弹出元素并存储到另一个数组中。以下是解决方案代码:

解决方案代码

import numpy as np

def is_balanced(s):
    stack = np.array([], dtype=str)
    bracket_map = {')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in bracket_map.values():
            stack = np.append(stack, char)
        elif char in bracket_map.keys():
            if len(stack) == 0 or stack[-1] != bracket_map[char]:
                return False
            # 模拟pop操作,截取前n-1个元素
            stack = stack[:-1]
        else:
            return False
    return len(stack) == 0

t = int(input("Count: "))
while t > 0:
    s = input()
    print("YES" if is_balanced(s) else "NO")
    t -= 1

内容的提问来源于stack exchange,提问作者Andyroid Gaming

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 12:17:31