LeetCode : Valid Parentheses [java]
2016-03-07 19:55
423 查看
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.
思路:使用堆栈存储,遇到配对就弹出,为空则恰好全部配对成功。
import java.util.Stack; public class Solution { public boolean isValid(String s) { Stack<Character> stack = new Stack<>(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); switch (ch) { case ')': if (!stack.isEmpty() && stack.peek() == '(') { stack.pop(); } else { stack.push(ch); } break; case ']': if (!stack.isEmpty() && stack.peek() == '[') { stack.pop(); } else { stack.push(ch); } break; case '}': if (!stack.isEmpty() && stack.peek() == '{') { stack.pop(); } else { stack.push(ch); } break; default: stack.push(ch); } } return stack.isEmpty(); } }
相关文章推荐
- 读取一个指定的*.Java文件,并打印在控制台上
- 怎么用Eclipse打开一个写好的项目
- Java基础复习,整理知识点
- JAVA Swing
- 出现R.java文件不见了的情况,或者R.java导入错误
- Java——面向对象(二)
- Myeclipse/Eclipse安装Maven环境
- RSA 加密解密 关于javax.crypto.BadPaddingException: Blocktype错误的几种解决方法
- 如何修改java String
- Quartz任务调度器与spring整合
- Java二维数组
- java 入门 运算符
- eclipse导入代码时中文乱码 解决方案
- Java出现No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing
- 【Spring】Spring Security 相关知识学习总结
- java api如何获取kafka所有Topic列表,并放置为一个list
- Spring返回方式总结
- 运行Struts2程序时出现异常
- 解决mac OS X 下出现的 java.net.UnknownHostException 异常
- Java线程栈的获取和分析