您的位置:首页 > 其它

LeetCode(49)-Valid Parentheses

2016-11-09 00:00 274 查看

题目:

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.

思路:

题意:一个字符串,只是包含括号,判断括号是不是合法的使用

这个问题的思路是使用栈,这一类对应的问题都是使用栈,遇到前括号压栈,遇到后括含出栈,是不是对应,看最后是不是为0
-

代码:

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