LeetCode -- Valid Parenthese
2015-10-12 20:27
429 查看
Question:
Given a string containing just the characters
The brackets must close in the correct order,
Analysis:
问题描述:给出一个字符串,包含
思路:一看到括号匹配问题肯定想到用栈。遇到左括号就进栈;遇到右括号若栈顶元素与之匹配则POP出栈顶元素,若不匹配则返回false。
注意特殊情况:如"{}[]()", 或者“{[}]”, 或者“{{}}{{”等情况。
Answer:
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.
Analysis:
问题描述:给出一个字符串,包含
'(',
')',
'{',
'}',
'['and
']'确定它是否是有效地匹配括号。
思路:一看到括号匹配问题肯定想到用栈。遇到左括号就进栈;遇到右括号若栈顶元素与之匹配则POP出栈顶元素,若不匹配则返回false。
注意特殊情况:如"{}[]()", 或者“{[}]”, 或者“{{}}{{”等情况。
Answer:
public class Solution { public boolean isValid(String s) { char[] ch = s.toCharArray(); int n = ch.length; if(ch.length == 0 || ch.length % 2 != 0) return false; if(ch[0] == '}' || ch[0] == ']' || ch[0] == ')') return false; Stack<Character> st = new Stack<Character>(); st.add(ch[0]); int i = 1; while(!st.isEmpty() && i < n) { if(ch[i] == '{' || ch[i] == '[' || ch[i] == '(') { st.add(ch[i]); i++; } else { if(st.isEmpty()) return false; char c = st.pop(); if(c == '{' && ch[i] != '}' || c == '[' && ch[i] != ']' || c == '(' && ch[i] != ')') return false; i++; if(i < n && (ch[i] == '{' || ch[i] == '[' || ch[i] == '(')) { st.add(ch[i]); i++; } } } System.out.println(i +" " +st.size()); if(!st.isEmpty() || i < n - 1) return false; return true; } }
相关文章推荐
- 见拦截导弹
- 什么是死锁及死锁的必要条件和解决方法【转】
- 博客集合
- dos下通过wmic命令查看硬盘和内存/CPU信息(windows自带命令查看硬件信息)
- c++调用lua时简单打印lua栈
- [[ViewController alloc]init]与[ViewController alloc]initWithNibName: bundle: ]的区别;
- iOS SDK详解之视频播放(AVPlayer)附Demo
- 正则匹配 符合以什么开头以什么结尾的
- PCB封装-正片与负片
- 第一个Servlet程序
- 并查集(Union-Find)算法介绍
- 20151012----思维导图整理
- 笔试常见问题汇总
- 基础,自己又容易忘记的,计算机基础知识
- 解决qcow2高版本兼容问题
- 从一道面试题谈linux下fork的运行机制
- C语言学习
- hdu 1166 敌兵布阵
- 1、C语言基本数据类型
- 20151012----面向对象