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.
括号匹配~我自己考虑到类似小括号包含中括号([])或者中括号包含大括号的情况可能是不正确的,但实际没有影响~不用额外考虑这样的情况,只有括号匹配即可。
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {//遍历方式简洁
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)//之前存储对应的括号,此处直接比较是否相等
return false;
}
return stack.isEmpty();
}
我的代码
class Solution {
public boolean isValid(String s) {
if(s.isEmpty())
return true;
Stack<Character> C = new Stack<Character>();
char now = '(';
char last = ')';
for (int i = 0; i < s.length(); i++) {
now = s.charAt(i);
if ((now == '(') || (now == '[') || (now == '{'))
C.push(now);
else {
if (C.isEmpty())
return false;
last = C.pop();
if ((now == ')') && (last != '('))
return false;
if ((now == ']') && (last != '['))
return false;
if ((now == '}') && (last != '{'))
return false;
}
}
if (C.isEmpty())
return true;
return false;
}
}