Valid Parentheses

来源:互联网 发布:vscode lua 编辑:程序博客网 时间:2024/05/17 18:23

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.

  1. 括号匹配问题
  2. 使用一个栈解决。
  3. 左括号如栈,然后右括号入栈,如果栈顶为对应左括号则出栈,依次进行。
  4. 最后栈为空说明都匹配上了,非空说明不匹配。
class Solution {public:    bool isValid(string s) {        stack<char> a;        for(char& n:s) {            switch(n) {                case'(':                case'{':                case'[': a.push(n); break;                case')': if(a.empty() || a.top()!='(') return false;  else a.pop(); break;                case'}': if(a.empty() || a.top()!='{') return false;  else a.pop(); break;                case']': if(a.empty() || a.top()!='[') return false;  else a.pop(); break;                default:;            }        }        return a.empty()?true:false;    }};
0 0