写一段代码,判断一个包括'{','[','(',')',']','}'的表达式是否合法(注意看样例的合法规则。) 给定一个表达式A,请返回一个bool值,代表它是否合法。
这道题比较奇怪,它的匹配规则并不是我们平时想想的那种匹配规则,例如:平时的匹配规则是()、{}、[]才能匹配,本题中(和} 、]、)都能匹配。所以做题时要好好审题。另外,本题中给的测试用例是错误的。
// ConsoleApplication5.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<vector>
#include<iostream>
#include<string>
#include <stack>
using namespace std;
class ChkExpression {
public:
bool chkLegal(string A) {
stack<char> inStack;
stack<char> outStack;
for (int i = 0; i < A.size(); i++)
{
inStack.push(A[i]);
}
while (!inStack.empty())
{
char ch = inStack.top();
bool flag = true;
cout << inStack.top() << " ";
if (!outStack.empty() )
{
cout << outStack.top() << endl;
}
else
{
cout << "空" << endl;
}
switch (ch)
{
case '}':
outStack.push('}');
inStack.pop();
break;
case ']':
outStack.push(']');
inStack.pop();
break;
case ')':
outStack.push(')');
inStack.pop();
break;
case '{':
if (!outStack.empty() )
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;
case '[':
if (!outStack.empty() )
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;
break;
case '(':
if (!outStack.empty() )
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;
/* case '{':
if (!outStack.empty() && outStack.top() == '}')
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;
case '[':
if (!outStack.empty() && outStack.top() == ']')
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;
case '(':
if (!outStack.empty() && outStack.top() == ')')
{
outStack.pop();
inStack.pop();
}
else
{
flag = false;
}
break;*/
default:
inStack.pop();
break;
}
if (flag == false)
{
break;
}
}
if (outStack.empty() && inStack.empty())
{
return true;
}
else
{
return false;
}
}
};
int main()
{
string A = "[a+b*(5-4)]*{x+b+b*(1+2)}";
ChkExpression ce;
cout << ce.chkLegal(A) << endl;
return 0;
}