LeetCode - Valid Parentheses
2015-12-20 08:12
357 查看
题目:
Given a string containing just the characters
The brackets must close in the correct order,
思路:
用栈来解决。
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.
思路:
用栈来解决。
package ds; import java.util.Stack; public class ValidParentheses { public boolean isValid(String s) { Stack<Character> stack = new Stack<Character>(); int len = s.length(); for (int i = 0; i < len; ++i) { char c = s.charAt(i); switch (c) { case '(': case '[': case '{': stack.push(c); break; case ')': if (stack.isEmpty() || stack.pop() != '(') return false; break; case ']': if (stack.isEmpty() || stack.pop() != '[') return false; break; case '}': if (stack.isEmpty() || stack.pop() != '{') return false; break; } } return stack.isEmpty(); } public static void main(String[] args) { // TODO Auto-generated method stub ValidParentheses v = new ValidParentheses(); // Test case 1 System.out.println(v.isValid("()[]}")); // Test case 2 System.out.println(v.isValid("(")); } }
相关文章推荐
- 对只转发结果集的无效操作:beforeFirst
- Leetcode: Lowest Common Ancestor of a Binary Tree
- Android - 设置ImageView为全屏显示
- Android应用开发基本流程及测试运行
- Leetcode: Lowest Common Ancestor of a Binary Search Tree
- 思想上移,行动下移——抽象工厂+反射+配置文件
- 【机房收费系统】数据库设计
- 支持向量机(SVM)非线性数据切割
- QQ音乐API
- bzoj3517 翻硬币 数学
- LeetCode - Remove Nth Node From End of List
- 【Beta阶段】第八次Scrum Meeting!
- error: 'for' loop initial declarations are only allowed in C99 mode
- sameersbn/gitlab6.9.2实战
- UVAlive2531 The K-League(最大流)
- 向操蛋的行规说NO!
- 2016太原网络营销师郭文军讲解如何运营自媒体下的【百度贴吧】
- 完全纯净!你的最佳PE工具箱-微PE
- C语言递归调用2:猜数小游戏
- Leetcode: Palindrome Linked List