题目:
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.
考察栈的基本使用,简单的入栈和出栈即可解决。刚看到了一种好玩的for循环格式,这里用一下。
public class Solution {
public boolean isValid(String s) {
Stack<Character> stackS = new Stack<Character>();
char[] arr = s.toCharArray();
for (char c : arr) {
if(stackS.isEmpty()){
stackS.push(c);
continue;
}
Character temp = stackS.pop();
// 配对时c不入栈
if (temp == '[' && c == ']') {
}
<span style="white-space:pre"> </span> else if (temp == '(' && c == ')') {
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span> else if (temp == '{' && c == '}') {
<span style="white-space:pre"> </span> }
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span> // 不配对时c入
<span style="white-space:pre"> </span> else {
<span style="white-space:pre"> </span> stackS.push(temp);
<span style="white-space:pre"> </span> stackS.push(c);
<span style="white-space:pre"> </span> }
}
return stackS.isEmpty();
}
}