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.
分析:
使用栈
代码:
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
using namespace std;
bool ValidParentTheses(string str){
int len = str.size();
string leftBracket = "([{";
string rightBracket = ")]}";
stack<char> sk;
for (int i = 0; i < len; i++)
{
if (leftBracket.find(str[i]) != string::npos)
{
sk.push(str[i]);
}
if (rightBracket.find(str[i]) != string::npos)
{
if (!sk.empty() && sk.top() == leftBracket[rightBracket.find(str[i])])
{
sk.pop();
}
else
return false;
}
}
if (!sk.empty())
return false;
return true;
}
int main()
{
string str = "()";
string str2 = "()[]";
string str3 = "(]";
string str4 = "([)]";
cout << boolalpha << ValidParentTheses(str) << endl;
cout << boolalpha << ValidParentTheses(str2) << endl;
cout << boolalpha << ValidParentTheses(str3) << endl;
cout << boolalpha << ValidParentTheses(str4) << endl;
system("pause");
return 0;
}
测试: