LeetCode20 Valid Parentheses的java 题解
2015-06-17 16:36
459 查看
题目:
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.
解题思路:
建立一个栈,输入如果是右括号直接压入栈,如果是左括号,若栈为空返回false,不为空就出栈,判断出栈的字符和输入的字符是否配对,处理完整个字符串后如果栈不为空返回false
代码:
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.
解题思路:
建立一个栈,输入如果是右括号直接压入栈,如果是左括号,若栈为空返回false,不为空就出栈,判断出栈的字符和输入的字符是否配对,处理完整个字符串后如果栈不为空返回false
代码:
public static boolean isValid(String s) { Stack<Character> stack=new Stack<Character>(); Hashtable<Character, Character> hashtable=new Hashtable<>(); hashtable.put('(', ')'); hashtable.put('{', '}'); hashtable.put('[', ']'); char[] input=s.toCharArray(); for(int i=input.length-1;i>=0;i--) { if(input[i]==')'||input[i]=='}'||input[i]==']') { stack.push(input[i]); } else { Character temp=null; if(stack.empty()) return false; else { temp=stack.pop(); } if(hashtable.get(input[i])!=temp) return false; } } if(stack.empty()) return true; else { return false; } }
相关文章推荐
- struts的modelDriver模型驱动运用
- Java中socket传送中文乱码问题解决方法
- 通过dom4j进行数据读取xml文件进行数据的读取操作
- JAVA串口开发学习笔记1
- Eclipse 中设置JVM 内存及JVM监控调优
- java获取当前年月日
- Java仿文库的基本方法(openoffice+swftools+flexPaper)
- jdk1.8新特性
- Spring集成Quartz定时任务框架介绍和Cron表达式详解
- Java多线程编程总结笔记——03概念与原理
- javal连接mysq数据库
- Java 锁
- eclipse文件恢复
- java中JFrame 窗口关闭时,弹出一个对话框提示是否确定关闭
- JAVA-实现POJO 到XML的相互转换
- 我的Java开发学习之旅------>在Dos环境下Java内部类的编译和运行
- SpringMVC+Spring3+Hibernate4开发环境的搭建
- Java相对路径读取文件
- Spring整合JMS(四)——事务管理
- Spring整合JMS(三)——MessageConverter介绍