题目描述:
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。
思路:
首先想到的肯定就是用栈来实现,先读取一个字符压入栈中,然后紧接其后读入一个字符串进行判断;
注:本系列所以代码都经过VS2015本地编译通过;
代码如下;
#include<stack>
#include<iostream>
using namespace std;
class Solution {
public:
bool isValid(string const& s) {
stack<char> valid;
string left = "([{";
string right = ")]}";
for (auto c : s) {
if (left.find(c) != string::npos)
valid.push(c);
else {
if (valid.empty() || valid.top() != left[right.find(c)])
return false;
else
valid.pop();
}
}
return valid.empty();
}
};
int main(int argc,char** argv) {
Solution test;
cout<<"Result:"<<test.isValid("()")<<endl;
system("pause");
return 0;
}
结果;