20. Valid Parentheses
2016-01-23 20:40
316 查看
Valid Parenthese
有效的圆括号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.
ps:题意很简单 使用stack 依次检测即可
public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); // Iterate through string until empty for(int i = 0; i<s.length(); i++) { // Push any open parentheses onto stack if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{') stack.push(s.charAt(i)); // Check stack for corresponding closing parentheses, false if not valid else if(s.charAt(i) == ')' && !stack.empty() && stack.peek() == '(') //stack.peek()是用来检测栈顶的元素 stack.pop(); else if(s.charAt(i) == ']' && !stack.empty() && stack.peek() == '[') stack.pop(); else if(s.charAt(i) == '}' && !stack.empty() && stack.peek() == '{') stack.pop(); else return false; } // return true if no open parentheses left in stack return stack.empty(); //此处注意不能直接返回true } }
相关文章推荐
- Swift 文档注释规范
- 【技巧】对拍
- Fix【推荐】
- Amazon RDS的通用型存储(SSD)
- Android BLE与终端通信(三)——客户端与服务端通信过程以及实现数据通信
- 包管理软件
- 使用 VisualVM 进行性能分析及调优
- 解决 Ubuntu 14.04 无法调节屏幕亮度的问题
- 挂载NTFS分区的两种方法
- 1-12 ARP协议
- IO流 创建java文件列表
- 蓝懿 ios技术交流和心得分享 2016年01月23日
- php 文件
- css中div布局学习(1)
- Java中final用法
- 1-VMware workstation认识
- Linux下Openssl的安装全过程
- 树---概念
- MinGW的下载和环境配置
- Python随手笔记第一篇(2)之初识列表和元组