【Leetcode-Easy-20】 Valid Parentheses
来源:互联网 发布:双拼net域名行情 编辑:程序博客网 时间:2024/04/30 22:44
【Leetcode-Easy-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.
思路
栈
程序
class Solution { public boolean isValid(String s) { LinkedList<String> stack = new LinkedList<>(); HashSet<String> set = new HashSet<>(); set.add("("); set.add("["); set.add("{"); for (int i = 0; i < s.length(); i ++){ String part = s.charAt(i) + ""; if (set.contains(part)) stack.push(part); else{ if (stack.isEmpty()) return false; String prepart = stack.pop(); if ("}".equals(part) && !"{".equals(prepart) || ")".equals(part) && !"(".equals(prepart) || "]".equals(part) && !"[".equals(prepart)){ return false; } } } return stack.isEmpty(); }}
更为巧妙的解法
public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') stack.push(')'); else if (c == '{') stack.push('}'); else if (c == '[') stack.push(']'); else if (stack.isEmpty() || stack.pop() != c) return false; } return stack.isEmpty();}
阅读全文
0 0
- [Leetcode 20, Easy] Valid Parentheses
- 【Leetcode-Easy-20】 Valid Parentheses
- 【leetcode】Valid Parentheses(easy)
- LeetCode-20-Valid Parentheses(堆栈)-Easy
- LeetCode OJ 20 Valid Parentheses [Easy]
- Leetcode 20. Valid Parentheses (Easy) (cpp)
- LeetCode-Easy刷题(5) 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
- [leetcode] 20 Valid Parentheses
- leetcode-20 Valid Parentheses
- BZOJ 1552: [Cerc2007]robotic sort/3506: [Cqoi2014]排序机械臂 splay
- 故障检测、性能调优与Java类加载机制
- 同时修改某一个数据库中所有表的所有字段的编码格式(mysql)
- linux中进程的管理
- CentOS 安装VNCserver 并开启远程桌面
- 【Leetcode-Easy-20】 Valid Parentheses
- 输入一个字符串,统计其出现频率最高的字母以及对应的次数
- 值得收藏的知识
- Vision_MATH_高精度
- 前端之js插件-fullPage
- (转)做个男人,做个成熟的男人,做个有城府的男人
- 对新概念应当”不求甚解“
- Ionic CLI使用教程指南
- Date与String相互转化 (含倒推时间段)