个人记录-LeetCode 20. Valid Parentheses
来源:互联网 发布:2选一数据选择器max 编辑:程序博客网 时间:2024/05/18 03:08
问题:
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.
问题的要求是:判断括号的匹配是否符合规则。
利用栈可以轻松解决。
代码示例:
public class Solution { public boolean isValid(String s) { if (s == null || s.length() < 1) { return true; } Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); ++i) { //'('、'['、'{'入栈;')'、']'、'}'出栈 if (s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') { stack.push(s.charAt(i)); } else if (s.charAt(i) == ')') { //判断出栈条件是否满足 if (!checkStack(stack, '(')) { return false; } } else if (s.charAt(i) == ']') { if (!checkStack(stack, '[')) { return false; } } else if (s.charAt(i) == '}') { if (!checkStack(stack, '{')) { return false; } } } //成功匹配后,栈最后应该是空的 return stack.empty(); } private static boolean checkStack(Stack<Character> stack, char wanted) { //出栈时,必须匹配;例如碰到')', 那么栈顶必须是'('才行 if (!stack.empty() && stack.peek() == wanted) { stack.pop(); return true; } return false; }}
0 0
- 个人记录-LeetCode 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- leetcode 20. Valid Parentheses
- 【LeetCode】20. Valid Parentheses
- leetcode 20. Valid Parentheses
- leetcode 20. Valid Parentheses
- LeetCode-20.Valid Parentheses
- LeetCode *** 20. Valid Parentheses
- LeetCode 20. Valid Parentheses
- jquery的四大选择器
- 第25节--聚类之K-means算法(下)
- Maven学习 (四) 使用Nexus搭建Maven私服
- Linux下Apache httpd安装及配置为服务
- LeetCode 401. Binary Watch
- 个人记录-LeetCode 20. Valid Parentheses
- 51nod 1003 阶乘后面0的数量
- apache php mysql 怎么理解他们工作流程
- LeetCode 217. Contains Duplicate
- 在原生态的zabbix3.0登录界面添加hand登录界面的样式
- 安卓、java常用文件操作(复制,读取,写入,转换等)
- 热衷分享永远不会错
- 标准I/O
- 杂花生树(二十)