您的位置:首页 > 其它

LeetCode-20-Valid Parentheses(有效的括号)

2017-07-22 20:35 453 查看
Q:

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:

中规中矩,用数据结构中的栈,如果遇到左括号,则入栈;遇到右括号,在栈不为空的情况下出栈进行括号匹配判断,若不匹配直接返回false。

Code:

public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(c=='('||c=='['||c=='{'){
stack.push(c);
}else if(c==')'){
if(!stack.isEmpty()&&'('==stack.peek()){
stack.pop();
}else{
return false;
}
}else if(c==']'){
if(!stack.isEmpty()&&'['==stack.peek()){
stack.pop();
}else{
return false;
}
}else if(c=='}'){
if(!stack.isEmpty()&&'{'==stack.peek()){
stack.pop();
}else{
return false;
}
}
}
return stack.isEmpty();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: