LeetCode[stack]: Valid Parentheses

时间:2014-11-05 09:19:22   收藏:0   阅读:300

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.

典型的栈的应用,直接附上代码:

C++ code
bool isValid(string s) { stack<char> parentheses; for (auto c : s) { if (c == ‘(‘ || c == ‘{‘ || c == ‘[‘) parentheses.push(c); else { if (parentheses.empty()) return false; else if (c == ‘)‘ && parentheses.top() != ‘(‘) return false; else if (c == ‘]‘ && parentheses.top() != ‘[‘) return false; else if (c == ‘}‘ && parentheses.top() != ‘{‘) return false; parentheses.pop(); } } return parentheses.empty(); }

原文:http://blog.csdn.net/chfe007/article/details/40798741

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!