20. Valid Parentheses
来源:互联网 发布:手机淘宝哪里投诉卖家 编辑:程序博客网 时间:2024/04/30 11:43
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.
思路:
- 将‘{’和‘}’、‘[’和‘]’、’(‘和‘)’放入到HashMap中
- 遍历字符串s,将‘{’‘[’‘(’入栈,如果是‘]’或‘}’或‘)’从map中取出其对应的字符和栈顶元素比较,相等出栈,否则,返回false;
- 判断栈中的元素是否为空,为空返回true,否则,返回false;
细节问题:
- 如果case为“}”或者“](){}”,是不是应该单独在考虑下,首字符的问题。有两种做法:第1种做法:先判断首字符,不为‘(’、‘{’、‘[’,直接返回false;第2种做法:在遍历字符串s中,通过使用标记位进行判断。
测试的所有case:
println(s.isValid("()[]{}")); println(s.isValid("()")); println(s.isValid("()}")); println(s.isValid("}()")); println(s.isValid("([)]")); println(s.isValid("}")); println(s.isValid(""));
代码:
if (s == null || s.equals("")) return true; Stack<Character> stack = new Stack<>(); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put(']', '['); map.put('}', '{'); char ch = '0'; boolean isFirst = true; for (int i = 0; i < s.length(); i++) { ch = s.charAt(i); if ('(' == ch || '{' == ch || '[' == ch) { stack.push(ch); isFirst = false; } else {// 处理“]”类型的case; if (isFirst) { return false; } if (!stack.empty() && stack.peek() == map.get(ch)) { stack.pop(); } else { return false; } } } if (stack.empty()) { return true; } else { return false; }
遇到问题:
编程的过程中,用到了Stack 对象 stack,stack.empty()和stack.isEmpty()两种方法的区别和联系,百度了下没有搜到?
- API是这样说的:
isEmpty()方法:—该方法是Vector类中的方法,Stack类继承了Vector
public boolean isEmpty()
测试此向量是否不包含组件。
指定者:
接口 Collection 中的 isEmpty
指定者:
接口 List 中的 isEmpty
覆盖:
类 AbstractCollection 中的 isEmpty
返回:
当且仅当此向量没有组件(也就是说其大小为零)时返回 true;否则返回 false。
empty()方法:
empty
public boolean empty()
测试堆栈是否为空。
返回:
当且仅当堆栈中不含任何项时返回 true;否则返回 false。
不知您是否看出来了什么???明白吗?
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
- .Net(C#)自定义WinForm控件之小结篇
- Git思维导图
- Mac电脑MAMP PRO集成环境Apache启动不了
- 欢迎使用CSDN-markdown编辑器
- onInterceptTouchEvent和onTouchEvent调用关系详解
- 20. Valid Parentheses
- idea常用快捷键设置(改为eclipse相似)
- MySQL服务器参数优化
- js去重
- iOS 原生二维码扫描、生成、识别
- Linux中的grep命令实例
- 安装mysql报错问题处理
- windows下Gulp入门详细教程
- Ubuntu 14.04 64 bit error while loading shared libraries: libgtk-x11-2.0.so.0