UVa 673 Parentheses Balance (stack)
题目描述 : 判断字符串是不是符合正确的表达式形式。
要点 : 考虑字符串为空的时候,用getline输入,每一次判断后如果为No则要清空栈。对称思想。
注意输入格式。
代码:
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
int main()
{
stack<int> s;
int n;
int value[200];
cin>>n;
cin.ignore();
string str;
while(n--)
{
getline(cin , str);
int len = str.size();
if(len == 0)
cout<<"Yes\n";
else
{
for(int i=0; i<len; i++)
{
if(str[i] == '(')
value[i] = 1;
if(str[i] == ')')
value[i] = -1;
if(str[i] == '[')
value[i] = 2;
if(str[i] == ']')
value[i] = -2;
}
for(int i=0; i<len; i++)
{
if(s.empty())
{
s.push(value[i]);
}
else
{
if(s.top() == (-value[i]) && s.top()>0)
s.pop();
else
s.push(value[i]);
}
}
if(s.empty())
cout<<"Yes\n";
else
{
cout<<"No\n";
while(!s.empty())
{
s.pop();
}
}
}
}
return 0;
}
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。








浙公网安备 33010602011771号