您的位置:首页 > 其它

leetcode-20. Valid Parentheses

2017-03-08 17:00 471 查看

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: