20. Valid Parentheses
来源:互联网 发布:域名紧急更新 编辑:程序博客网 时间:2024/04/30 15:50
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.length()%2==1 || s.length()==0) return false; Map<Character, Character> map = new HashMap<Character, Character>();//hashmap存括号对,key存括号左半部分,value存括号有半部分 map.put('(', ')'); map.put('[', ']'); map.put('{', '}'); Deque<Character> stack = new LinkedList<>();//堆栈存括号对的左半部分 for (int i = 0; i < s.length(); i++) { char curr = s.charAt(i); //判断字符,如果存在于map中key中,则是左半部分,存于堆栈中。如果存在于map中的value中,则是右半部分,和堆栈中的栈顶元素比较,若相等,括号配对成功;否则返回括号配对失败。 if (map.keySet().contains(curr)) { stack.addFirst(curr); } else if (map.values().contains(curr)) { if (!stack.isEmpty() && map.get(stack.getFirst()) == curr) { stack.removeFirst(); } else { return false; } } } return stack.isEmpty(); }}
0 0
- LeetCode 20. Valid Parentheses
- [LeetCode] 20.Valid Parentheses
- LeetCode --- 20. Valid Parentheses
- LeetCode 20.Valid Parentheses
- [Leetcode] 20. Valid Parentheses
- 20.Valid Parentheses
- 20.Valid Parentheses
- 20. Valid Parentheses
- 【leetcode】20. Valid Parentheses
- [leetcode] 20.Valid Parentheses
- [leetcode] 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- 20. Valid Parentheses
- Leetcode 20. Valid Parentheses
- 20. Valid Parentheses LeetCode
- 20. Valid Parentheses
- 20. Valid Parentheses
- Linux 线程同步的三种方法
- 迭代器用法实例
- 如何总结和整理学术文献?
- java三种定时任务
- thymeleaf国际化过程中由于版本问题出现错误!
- 20. Valid Parentheses
- spring两种定时任务
- 微米系统二次开发记录
- 基于Android平台的五子棋小游戏------AI篇
- startActivityForResult 和 onActivityResult 问题
- 学习SLAM需要哪些预备知识?
- 为你的仓库自动创建.gitignore
- NULL 是什么 && 为什么要使用 strlen(s) + 1
- android炫酷的复合文本--SpannableString