给定仅包含“()[]{}”六种括号的字符串,请你判断该字符串中,括号的匹配是否是合法的,也就是对应括号的数量、嵌套顺序完全正确。
输入格式:
第一行一个整数T(T<=10) 其后T行每行一个字符串只包含[{()}]六种字符(字符串长度2e5以内)
输出格式:
对于每个字符串,匹配输出Yes,否则输出No
输入样例:
2
{()[]}
([)]
输出样例:
Yes No
报段错误代码段
原因:这一段会出现访问非法内存的情况,char a = st.top();赋值时有可能栈空,没有栈顶。
else if((str[i] == ')') || (str[i] == ']') || (str[i] == '}'))
{
char a = st.top();
if((a == '(' && str[i] == ')') || (a == '{' && str[i] == '}') || (a == '[' && str[i] == ']'))
{
st.pop();
}
else return false;
}
AC代码
#include <iostream>
#include <stack>
#include <string>
using namespace std;
stack<char> st;
bool ismatch(string str)
{
int n = str.length();
if(n % 2 != 0) return false;
else
{
for(int i = 0; i < n; i++)
{
if( (str[i] == '(')|| (str[i] == '[')|| (str[i] == '{'))
{
st.push(str[i]);
}
else
{
if(!st.empty()) //注意先判断栈空情况
{
if((st.top() == '(' && str[i] == ')') || (st.top() == '{' && str[i] == '}') || (st.top() == '[' && str[i] == ']'))
{
st.pop();
}
else return false;
}
else return false;
}
}
}
return true;
}
int main()
{
int T;
cin >> T;
string str;
while(T--)
{
cin >> str;
if(ismatch(str) == false) cout << "No" <<endl;
else cout << "Yes" <<endl;
}
return 0;
}