这是一道比较经典的使用栈的题。总的来说难度不大,比较有趣。
建议先自己玩玩,没什么思路可以看看我这边的题解。
class Solution {
public static boolean isValid(String s) {
if(s.isEmpty())return true;
else {
int slength = s.length();
int point = 0;
Stack<Character> bracketStack = new Stack<Character>();
char bracket;
while( point < slength ) {
if(bracketStack.isEmpty()) {
bracketStack.push(s.charAt(point));
point++;
continue;
}
bracket = s.charAt(point);
//40是“(”,41是“)”
if(bracketStack.peek()==40&&bracket==41) {
bracketStack.pop();
}
//91是“[”,92是“]”
else if(bracketStack.peek()==91&&bracket==93) {
bracketStack.pop();
}
//123是“{”,125是“}”
else if(bracketStack.peek()==123&&bracket==125) {
bracketStack.pop();
}
else {
bracketStack.push(bracket);
}
point++;
}
if(bracketStack.isEmpty())return true;
return false;
}
}
}