题目
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.
这种括号匹配用栈很方便,这里在判断括号是否匹配时利用了ASCII码的大小。
代码
import java.util.Stack;
public class ValidParentheses {
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 (stack.isEmpty() || c - stack.pop() > 2) {
return false;
}
}
}
return stack.isEmpty();
}
}
本文介绍了一种使用栈解决括号匹配问题的有效方法,并通过Java实现了一个简单的验证算法。该算法能够判断输入字符串中的括号是否正确配对。
303

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



