有两个需要注意的点:
1.(sta.empty()||sta.top() != '[' )这个判断是从左到右的短路判断,应该先判空,不空再判断是否匹配,否则sta.top()可能导致程序异常
2.循环结束后,栈为空才匹配完成
#include<stdio.h>
#include<stack>
#include<string>
#include <iostream>
using namespace std;
int main() {
string str;
getline(cin, str);
stack<char> sta;
for (int i = 0; i < str.size(); i++) {
if (str[i] == '[' || str[i] == '(') {
//进栈
sta.push(str[i]);
}
else if (str[i] == ']') {
if (sta.empty()||sta.top() != '[' ) {
printf("false\n");
return 0;
}
//匹配出栈
sta.pop();
}
else if (str[i] == ')') {
if (sta.empty()||sta.top() != '(') {
printf("false\n");
return 0;
}
//匹配出栈
sta.pop();
}
}
if (sta.empty()) {
printf("true\n");
}
else {
printf("false\n");
}
return 0;
}

京公网安备 11010502036488号