Valid Parentheses
2015-08-29 15:11
274 查看
Given a string containing just the characters
determine if the input string is valid.
The brackets must close in the correct order,
all valid but
not.
'(',
')',
'{',
'}',
'['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 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.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(); }
相关文章推荐
- Maven 打jar包
- mac一些快捷键
- Binary Indexed Tree 树状数组
- poj 2762 Going from u to v or from v to u?【强连通分量缩点+拓扑排序】
- [树结构]二叉树的重建和序列化
- mfc 利用CImage类解决多个PNG多次叠加的闪烁问题
- 2015/8/28的面试题
- 搭建SVN
- oracle11g 安装步骤详解
- Baby-Step-Giant-Step 很酷的算法
- hdu 4738 2013杭州赛区网络赛 桥+重边+连通判断 ***
- 细细品味大数据--初识hadoop
- Linux 下ssh创建ip加密码隧道
- qsort函数用法
- 关于CSDN-markdown编辑器
- 史上最全 ——LINQ to SQL语句
- js SyntaxError: unterminated string literal
- POJ1745 Divisibility(dp)
- Could not load the Tomcat server configuration at \Servers\Tomcat v7.0 Server at localhost-config
- mysql字符集设置浅了解