昨天OJ崩了结果就忘了。。。今天补上。
Description
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
Input
()
Output
True
Input
([)
False
False
大意是一串括号,如果是按顺序关上的就是Valid的,否则不是。思路还是上次的括号匹配算法,不过这个比那个简单多了,只要在关括号时判断与栈顶是否匹配即可,不匹配直接返回false。
代码
#include<iostream>
#include<stack>
#include<string>
#include<vector>
using namespace std;
int main()
{
stack<char>s;
string ss;
cin >> ss;
for (int i = 0; i < ss.size(); i++)
{
if (ss[i] == '(' || ss[i] == '{' || ss[i] == '[')
s.push(ss[i]);
else
{
if (!s.empty()) {
if (ss[i] == ')')
{
if (s.top() != '(')
{
cout << "False" << endl;
return 0;
}
else
s.pop();
}
else if (ss[i] == '}')
{
if (s.top() != '{')
{
cout << "False" << endl;
return 0;
}
else
s.pop();
}
else if (ss[i] == ']')
{
if (s.top() != '[')
{
cout << "False" << endl;
return 0;
}
else
s.pop();
}
}
}
}
if (!s.empty())
{
cout << "False" << endl;
return 0;
}
else
cout << "True" << endl;
return 0;
}