问题描述:
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.
原问题链接:https://leetcode.com/problems/valid-parentheses/
问题分析
这个问题相对来说比较简单,我们要判断给定的字符串是否符合合法的符号对。可以用一个栈来辅助处理。当我们遍历数组的时候,碰到左边括号的时候就压栈。如果碰到右边括号的时候就先看是否和栈顶的元素形成一个合法的括号。如果是,则弹出栈顶的元素,否则就返回非法的结果。在最终这个流程处理结束之后再看栈是否为空,如果栈为空表示达到一个合法的结果,否则就是非法的。
针对具体的实现细节,里面也有一些小的可以优化的地方。比如说当我们判断当前输入的字符不是左括号的时候,作为合法的输入,栈应该是非空的。我们可以在这里判断一下,如果栈是空的就可以直接返回了。这样可以跳过一些情况。详细的实现如下:
public class Solution {
public boolean isValid(String s) {
if(s == null || s.length() < 1) return true;
Stack<Character> stack = new Stack<>();
for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == '(' || c == '[' || c == '{') stack.push(c);
else {
if(stack.isEmpty()) return false;
if(c == ')') {
if(stack.peek() == '(') stack.pop();
else return false;
} else if(c == ']') {
if(stack.peek() == '[') stack.pop();
else return false;
} else if(c == '}') {
if(stack.peek() == '{') stack.pop();
else return false;
} else return false;
}
}
return stack.isEmpty();
}
}