15算法课程 20. Valid Parentheses

来源:互联网 发布:上海 软件设计师报名 编辑:程序博客网 时间:2024/06/06 08:24

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.

solution:

使用栈进行配对

code:

class Solution {  public:      bool isValid(string s) {          stack<char> paren;          for(auto c : s){              switch(c){                  case '(':                  case '{':                  case '[': paren.push(c); break;                  case ')': if(paren.empty() || paren.top() != '(') return false; else paren.pop(); break;                  case '}': if(paren.empty() || paren.top() != '{') return false; else paren.pop(); break;                  case ']': if(paren.empty() || paren.top() != '[') return false; else paren.pop(); break;                  default: ;              }          }          return paren.empty();      }  };  


原创粉丝点击