Leetcode:Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

#include<stack>
class Solution {
public:
bool isValid(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

int len = s.size();

if( len == 0 )
{
return false;
}

stack<char> my_stack;

if( len % 2 == 0 )
{
for( int i = 0; i < len ; ++i )
{
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
{
my_stack.push(s[i]);
continue;
}
else if( (s[i] == ')' || s[i] == ']' || s[i] == '}')&& !my_stack.empty())
{
switch(s[i])
{
case ')':
if(my_stack.top() == '(')
{
my_stack.pop();
break;
}
case ']':
if(my_stack.top() == '[')
{
my_stack.pop();
break;
}
case'}':
if(my_stack.top() == '{')
{
my_stack.pop();
break;
}
default:
return false;

}
}
else
return false;
}

if(my_stack.empty())
return true;
}

return false;
}
};

posted @ 2013-05-18 14:37  NinaGood  阅读(600)  评论(0编辑  收藏  举报