Valid Parentheses
题目:
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>
using namespace std;
class Solution {
public:
bool isValid(string s) {
char a[100];
for(int i=0;i<100;i++){
a[i] = '0';
}
int end=0;
for(int i = 0;i<s.size();i++){
if(a[end]=='('){
if(s.at(i)==')'){
a[end] = '0';
if(end>0)
end--;
}else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
a[++end]=s.at(i);
}else{
return false;
}
}else if(a[end]=='['){
if(s.at(i)==']'){
a[end] = '0';
if(end>0)
end--;
}else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
a[++end]=s.at(i);
}else{
return false;
}
}else if(a[end]=='{'){
if(s.at(i)=='}'){
a[end] = '0';
if(end>0)
end--;
}else if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
a[++end]=s.at(i);
}else{
return false;
}
}else{
if(s.at(i)=='('||s.at(i)=='['||s.at(i)=='{'){
a[end] = s.at(i);
}else{
return false;
}
}
}
if(a[end]!='0'){
return false;
}
return true;
}
};
int main(int argc, const char * argv[]) {
Solution a;
cout<<a.isValid("{{})")<<endl;
return 0;
}