#3722. [GESP202409 六级 C++] 第 4 题

[GESP202409 六级 C++] 第 4 题

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

#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();

{{ select(1) }}

  • A
  • B
  • C
  • D