第23826题 单选题
以下C++代码用于检查字符串括号是否匹配,横线处应填入的代码是?

采用如下代码实现检查输入的字符串括号是否匹配,横线上应填入的代码为( )。

#include <iostream>
#include <stack>
#include <string>
using namespace std;

bool is_valid(string s) {
    stack<char> st;
    char top;
    for (char& ch : s) {
        if (ch == '(' || ch == '{' || ch == '[') {
            st.push(ch);    // 左括号入栈
        }
        else
        {
            if (st.empty())
                return false;
            ________________________ // 在此处填入代码
            if ((ch == ')' && top != '(') ||
                (ch == '}' && top != '{') ||
                (ch == ']' && top != '[')) {
                return false;
            }
        }
    }
    return st.empty();    // 栈为空则说明所有括号匹配成功
}
A

top = st.top(); st.pop();

B

st.pop(); top = st.top();

C

st.pop(); top = st.front();

D

top = st.front(); st.pop();

程序运行统计
暂无判题统计
提交0次 正确率0.00%
答案解析