class Solution {
public boolean isValid(String s) {
//使用栈
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i ++){
if (s.charAt(i) == '(')
stack.push(s.charAt(i));
if (s.charAt(i) == '[')
stack.push(s.charAt(i));
if (s.charAt(i) == '{')
stack.push(s.charAt(i));
if ( s.charAt(i) == ')'){
if (!stack.empty() && stack.peek() == '(')
stack.pop();
else return false;
}
if (s.charAt(i) == ']'){
if (!stack.empty() && stack.peek() == '[')
stack.pop();
else return false;
}
if (s.charAt(i) == '}'){
if (!stack.empty() && stack.peek() == '{')
stack.pop();
else return false;
}
}
if (stack.empty())
return true;
return false;
}
}
自己写的竟然只击败了7%…
class MinStack {
Stack<Integer> s = new Stack<>();
ArrayList<Integer> minList = new ArrayList<>();
int idx = -1;
int min = 2147483647;
/** initialize your data structure here. */
public MinStack() {
}
public void push(int val) {
//比较的时候要比较整个minList的最小值,在常数范围求最小
min = Math.min(val, (idx >= 0)?minList.get(idx):min);
minList.add(min);
idx++;
s.push(val);
}
public void pop() {
min = 2147483647;
if (idx >= 0)
{
minList.remove(idx);
idx--;
}
s.pop();
}
public int top() {
return s.peek();
}
public int getMin() {
System.out.println(idx);
return minList.get(idx);
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
未完待续…`