20.有效的括号
可以做,也就是普通括号匹配问题。可能我还做麻烦了。
class Solution {
public boolean isValid(String s) {
Stackstack=new Stack<>();
int n=s.length();
int i=0;
for(i=0;iif(s.charAt(i)=='('||s.charAt(i)=='['||s.charAt(i)=='{')
stack.push(s.charAt(i));
if(s.charAt(i)==')'){
if(!stack.isEmpty()&&stack.pop()=='('){}
else return false;}
if(s.charAt(i)==']'){
if(!stack.isEmpty()&&stack.pop()=='['){}
else return false;
}
if(s.charAt(i)=='}'){
if(!stack.isEmpty()&&stack.pop()=='{'){}
else return false;
}
}
if(stack.isEmpty())
return true;
else return false;
}
}
232.用栈实现队列
不会,需要用两个栈。
class MyQueue {
DequeinStack;
DequeoutStack; public MyQueue() {
inStack = new ArrayDeque();
outStack = new ArrayDeque();
}public void push(int x) {
inStack.push(x);
}public int pop() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.pop();
}public int peek() {
if (outStack.isEmpty()) {
in2out();
}
return outStack.peek();
}public boolean empty() {
return inStack.isEmpty() && outStack.isEmpty();
}private void in2out() {
while (!inStack.isEmpty()) {
outStack.push(inStack.pop());
}
}
}