题目描述
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
输入
多组数据
每组是一个由'(',')','{','}','[',']' 组成的括号序列
每组字符串长度不超过50。
输出
如果有效输出true, 否则输出false。
样例输入
()
()[]{}
(]
([)]
{[]}
样例输出
true
true
false
false
true
#include<iostream>
#include<string>
using namespace std;
class stack
{
private:
char *p;
int top, maxsize;
public:
stack(int sz)
{
top = -1;
maxsize = sz;
p = new char[sz];
}
bool isempty() { return top == -1; }
bool isfull() { return top == maxsize - 1; }
bool pop() { if (isempty()) return false; top--; return true; }
bool push(char a) { if (isfull()) return false; p[++top] = a; return true; }
bool gettop(char&a) {
if (isempty())
return false;
a = p[top];
return true;
}
};
bool s(char a, char b)
{
return (a == '[' && b == ']') || (a == '(' && b == ')') || (a == '{' && b == '}');
}
int main()
{
char a, q;
string m;
int i, t;
while (cin >> m)
{
stack *p = new stack(50);
t = m.length();
for (i = 0; i < t;i++)
{
a = m[i];
if (a == '[' || a == '(' || a == '{')
p->push(a);
else if (a == ']' || a == ')' || a == '}')
if (p->isempty())
{
cout << "false"; break;
}
else
{
p->gettop(q);
if (s(q, a))
p->pop();
else
{
cout << "false";
break;
}
}
}
if (i == t)
if (p->isempty()) cout << "true";
else cout << "false";
delete[]p;
}
return 0;
}