题目:https://oj.leetcode.com/problems/valid-parentheses/
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.
算法分析:时间复杂度O(n!),空间复杂度O(n)
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
switch (s.charAt(i)) {
case '(':
stack.push('(');
break;
case '{':
stack.push('{');
break;
case '[':
stack.push('[');
break;
case ')':
if(!stack.isEmpty() && stack.peek()=='(') {
stack.pop();
}else {
return false;
}
break;
case '}':
if(!stack.isEmpty() && stack.peek()=='{') {
stack.pop();
}else {
return false;
}
break;
case ']':
if(!stack.isEmpty() && stack.peek()=='[') {
stack.pop();
}else {
return false;
}
break;
default:
return false;
}
}
if(stack.isEmpty) {
return true;
}else {
return false;
}
}
}
本文讨论了如何使用Java实现有效括号验证算法,包括使用栈来处理不同类型的括号,并检查它们是否按照正确的顺序闭合。
279

被折叠的 条评论
为什么被折叠?



