有效括号
Click here for leetcode details
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0){
return false;
}
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if (c == '(' || c == '[' || c == '{'){
stack.push(c);
//这里容易漏掉,需注意
} else if(stack.empty() && (c == ')' || c == ']'||c == '}')){
return false;
}else{
char a = stack.pop();
if (a == '(' && c != ')'){
return false;
}
if (a == '[' && c != ']'){
return false;
}
if (a == '{' && c != '}'){
return false;
}
}
}
return stack.empty();
}
}
最小栈
Click here for leetcode details
class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
public MinStack() {
stack = new Stack();
minStack = new Stack();
}
public void push(int val) {
stack.push(val);
if(minStack.empty() || minStack.peek() > val){
minStack.push(val);
} else {
//注意这里,如果不push自身的话,pop会空栈异常
minStack.push(minStack.peek());
}
}
public void pop() {
stack.pop();
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}
网友评论