leetcode-20. Valid Parentheses

来源:互联网 发布:linux mint 18.2 安装 编辑:程序博客网 时间:2024/06/06 01:16

leetcode-20. 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.Subscribe to see which companies asked this question.

栈的使用,明白pop是不要参数的,直接p.pop( )

class Solution {public:    bool isValid(string s) {        stack<char> p;        for(int i = 0; i < s.size(); ++i){            if(s[i] == '(' || s[i] == '[' || s[i] == '{')                p.push(s[i]);            else{                if(p.empty()) return false;                if(s[i] == ')' && p.top() != '(') return false;                if(s[i] == ']' && p.top() != '[') return false;                if(s[i] == '}' && p.top() != '{') return false;                else                     p.pop();       //栈的操作,pop的时候直接pop就行,不用加参数            }        }         if(p.empty())             return true;         else            return false;    }};
0 0
原创粉丝点击