您的位置:首页 > 编程语言 > Java开发

Valid Parentheses LeetCode java

2015-12-29 14:53 459 查看
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的特性,来进行比较。为(,【,{则直接入栈,为)】}则从stack弹出顶部的元素进行比较。

代码如下
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();

char[] c = s.toCharArray();

for(int i = 0; i<c.length;i++){
if(c[i] == '(' || c[i] == '[' || c[i] == '{'){
stack.push(c[i]);
}else if(c[i] == ')' || c[i] == ']' ||c[i] == '}'){
if(stack.empty()){
return false;
}else{
char ch = stack.pop();
if( ch == '(' && c[i] == ')')continue;
if( ch == '[' && c[i] == ']')continue;
if( ch == '{' && c[i] == '}')continue;
else return false;
}
}
}
if(stack.empty()) return true;
else return false;
}
}



95c6
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode