AI题库 · GESP-C++六级题库
题目分享 #20866
采用如下代码实现检查输入的字符串括号是否匹配,横线上应填入的代码为( )。
#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();
AI题库 · 编程考级与信奥赛真题库
查看答案 →
复制链接后可在微信、QQ、小红书等平台粘贴分享;答案与解析在题目页。