{ }codelper
栈判断函数P0040

括号匹配

给出一行只由括号字符 ( ) [ ] { } 组成的字符串。
如果每个左括号都按正确顺序与同类的右括号配对,输出 "是",否则输出 "否"。
正确顺序是指:每出现一个右括号,它必须与尚未闭合的左括号中最后打开的那个同类。
例如 "{[()]}" 和 "()[]" 是 yes,"([)]"、"(("、")(" 是 no。

输入
字符串长度为 1 到 10,000。
除 ( ) [ ] { } 外没有其他字符或空格。
输出
yes 或 no
样例 1 · stdin
{[()()]}
stdout
是
样例 2 · stdin
([)]
stdout
否
main.py
输入(stdin)

运行时这些行会依次作为 input()/标准输入传入(运行中不会等待输入)。

$ 就绪

请在电脑上打开以编写和运行代码。在手机上可以查看题目和题解。

其他语言怎么写?查看各语言题解 · 8 种语言题解

这是栈的问题:左括号入栈,遇到右括号就弹出栈顶比较种类。
三个陷阱:只按种类数个数会漏掉 "([)]";遇到右括号时不检查栈是否为空,")" 会让 Python 的 pop() 抛出 IndexError,在 C++ 中对空 std::stack 调用 top() 是未定义行为;最后不检查栈是否为空,"(((" 会被判为 yes。
栈工具:Python list 的 append/pop,JavaScript、TypeScript 数组的 push/pop,Java ArrayDeque(比旧的 Stack 类更推荐),C# Stack<char>,C++ std::stack(top() 查看、pop() 丢弃,分两步),C 用数组加一个栈顶下标。
Craykon 用列表:stack.添加(c),栈顶是 stack[stack.数量 - 1],弹出用 stack.按位置移除(stack.数量 - 1);Craykon 列表最多只能放 10,000 个,所以长度上限定为 10,000。

Pythonmain.py · 12 行
def is_balanced(s):    match = {")": "(", "]": "[", "}": "{"}    stack = []    for c in s:        if c in "([{":            stack.append(c)        elif not stack or stack.pop() != match[c]:            return False    return not stack  print("是" if is_balanced(input().strip()) else "否")
JavaScriptmain.js · 13 行
const s = require("fs").readFileSync(0, "utf8").trim(); function isBalanced(s) {  const match = { ")": "(", "]": "[", "}": "{" };  const stack = [];  for (const c of s) {    if ("([{".includes(c)) stack.push(c);    else if (stack.length === 0 || stack.pop() !== match[c]) return false;  }  return stack.length === 0;} console.log(isBalanced(s) ? "是" : "否");
TypeScriptmain.ts · 14 行
import { readFileSync } from "node:fs";const s: string = readFileSync(0, "utf8").trim(); function isBalanced(s: string): boolean {  const match: Record<string, string> = { ")": "(", "]": "[", "}": "{" };  const stack: string[] = [];  for (const c of s) {    if ("([{".includes(c)) stack.push(c);    else if (stack.length === 0 || stack.pop() !== match[c]) return false;  }  return stack.length === 0;} console.log(isBalanced(s) ? "是" : "否");
JavaMain.java · 25 行
import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.ArrayDeque;import java.util.Deque; public class Main {    static boolean isBalanced(String s) {        Deque<Character> stack = new ArrayDeque<>();        for (char c : s.toCharArray()) {            if (c == '(' || c == '[' || c == '{') {                stack.push(c);            } else {                char open = c == ')' ? '(' : c == ']' ? '[' : '{';                if (stack.isEmpty() || stack.pop() != open) return false;            }        }        return stack.isEmpty();    }     public static void main(String[] args) throws IOException {        String s = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();        System.out.println(isBalanced(s) ? "是" : "否");    }}
C#Main.cs · 29 行
using System;using System.Collections.Generic; class Program{    static bool IsBalanced(string s)    {        var stack = new Stack<char>();        foreach (char c in s)        {            if (c == '(' || c == '[' || c == '{')            {                stack.Push(c);            }            else            {                char open = c == ')' ? '(' : c == ']' ? '[' : '{';                if (stack.Count == 0 || stack.Pop() != open) return false;            }        }        return stack.Count == 0;    }     static void Main()    {        string s = Console.ReadLine().Trim();        Console.WriteLine(IsBalanced(s) ? "是" : "否");    }}
C++main.cpp · 23 行
#include <iostream>#include <stack>#include <string> bool isBalanced(const std::string& s) {    std::stack<char> st;    for (char c : s) {        if (c == '(' || c == '[' || c == '{') {            st.push(c);        } else {            char open = c == ')' ? '(' : c == ']' ? '[' : '{';            if (st.empty() || st.top() != open) return false;            st.pop();        }    }    return st.empty();} int main() {    std::string s;    std::cin >> s;    std::cout << (isBalanced(s) ? "是" : "否") << '\n';}
Cmain.c · 24 行
#include <stdbool.h>#include <stdio.h> static char s[10001], stack[10000]; bool is_balanced(const char *s) {    int top = 0;    for (int i = 0; s[i]; i++) {        char c = s[i];        if (c == '(' || c == '[' || c == '{') {            stack[top++] = c;        } else {            char open = c == ')' ? '(' : c == ']' ? '[' : '{';            if (top == 0 || stack[--top] != open) return false;        }    }    return top == 0;} int main(void) {    scanf("%10000s", s);    puts(is_balanced(s) ? "是" : "否");    return 0;}
Craykonmain.cray · 28 行
짝맞나(s){    stack = [];    遍历 (c 在 s)    {        如果 (c == "(" || c == "[" || c == "{")        {            stack.添加(c);        }        否则        {            如果 (stack.数量 == 0)            {                返回 假;            }            top = stack[stack.数量 - 1];            stack.按位置移除(stack.数量 - 1);            如果 (c == ")" && top != "(" || c == "]" && top != "[" || c == "}" && top != "{")            {                返回 假;            }        }    }    返回 stack.数量 == 0;} s = 控制台.读行().去空白();控制台.输出(짝맞나(s) ? "是" : "否");