LeetCode 20 Valid Parentheses
2015-08-10 16:05
330 查看
Valid Parentheses
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.
解题思路:这是一个简单的括号匹配问题,实现一个栈来进行匹配分析就可以。为了化简逻辑上的复杂度,我选择使用两个栈,一个栈作为符号存储,一个栈作为符号的下标存储,这也是为了便于匹配而实现的。通过下标栈的实现,不再需要单独的匹配的代码,只需要比较下标即可。当遇到后括号的时候,检索对应的下标栈,并将下标对应的数组值与当前括号比较,若相等,则说明括号匹配。如“()”第一个括号进入stack栈,check栈记录为0,遇到第二个括号的时候,check记录0对应的ch1值为")“,符合匹配。
代码如下:
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.
解题思路:这是一个简单的括号匹配问题,实现一个栈来进行匹配分析就可以。为了化简逻辑上的复杂度,我选择使用两个栈,一个栈作为符号存储,一个栈作为符号的下标存储,这也是为了便于匹配而实现的。通过下标栈的实现,不再需要单独的匹配的代码,只需要比较下标即可。当遇到后括号的时候,检索对应的下标栈,并将下标对应的数组值与当前括号比较,若相等,则说明括号匹配。如“()”第一个括号进入stack栈,check栈记录为0,遇到第二个括号的时候,check记录0对应的ch1值为")“,符合匹配。
代码如下:
public boolean isValid(String s) { char []stack = new char[1000]; int []check = new int[1000]; //记录下标 便于匹配 char []ch ={'(','{','['}; char []ch1 = {')','}',']'}; int index = 0;//数组下标 for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(c==ch[0]||c==ch[1]||c==ch[2]){ if(c==ch[0]){ check[index]=0; } if(c==ch[1]){ check[index]=1; } if(c==ch[2]){ check[index]=2; } stack[index++]=c; }else if(c==ch1[0]||c==ch1[1]||c==ch1[2]){ if(index<=0){ return false; } if(ch1[check[index-1]]==c){ index--; continue; }else{ return false; } } } if(index>0){ return false; } return true; }
相关文章推荐
- CocoaPods pod install/pod update更新慢的问题
- 树链剖分
- UVA 707 - Robbery【记忆化搜索】
- QT5的移植与错误总结
- 混合高斯模型(Mixtures of Gaussians)和EM算法
- hdu5353 Average
- 栈的顺序存储结构
- hdu 1028 Ignatius and the Princess III +hdu 1085 Holding Bin-Laden Captive!(母函数)
- nginx + unicorn 配置
- 76 php 页面数据格式化
- 关于升级Xcode版本后插件不能用的问题解决
- js常用正则表达式
- TCP echo demo
- myeclipse安装SVN插件
- java的变量和方法,实例化new
- IOS-开发小记 填坑之旅
- URAL 1519 基础插头DP
- sts 框架新建以及 网站部署
- 二叉树
- sql优化