Valid Parentheses

来源:互联网 发布:网络被攻击 编辑:程序博客网 时间:2024/05/22 13:02

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.


class Solution {public:    bool isValid(string s) {   int nLen=s.length();   int i=0;   stack<char>  cs;   while(i<nLen)   {   switch(s[i])   {      case '[':  case '{':  case '(':  cs.push(s[i]);  break;  case ']':  {  if(!cs.empty() && cs.top()=='[')  {  cs.pop();  break;  }  else  {  return false;  }  }  case '}':  {  if(!cs.empty() && cs.top()=='{')  {  cs.pop();  break;  }  else  {  return false;  }  }  case ')':  {  if(!cs.empty() && cs.top()=='(')  {  cs.pop();  break;  }  else  {  return false;  }  }  default:  break;   }   ++i;   }   if(cs.empty())   {      return true;   }   else   {   return false;   }            }};


0 0
原创粉丝点击