目录
用栈实现队列
正解:
class MyQueue { //假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作) Stack<Integer> stackIn,stackOut; public MyQueue() { stackIn=new Stack<>(); stackOut=new Stack<>(); } public void push(int x) { //将元素 x 推到队列的末尾 stackIn.push(x); } //这里抽象一个函数,其功能是把stackIn 的元素出栈到 stackOut public void dumpStackIn(){ if(!stackOut.isEmpty()) return;//如果stackOut栈有元素,就不管,反之出栈[while循环实现] while(!stackIn.isEmpty()){ stackOut.push(stackIn.pop()); } } public int pop() { // 删除并返回队头元素 dumpStackIn(); return stackOut.pop(); } public int peek() { // 查看队头元素不是删除 dumpStackIn(); return stackOut.peek(); } public boolean empty() { // 如果队列为空,返回 true ;否则,返回 false //这里就是判断两个栈是否为空 return stackOut.isEmpty() && stackIn.isEmpty(); } }
用队列实现栈
正解:
class MyStack { Queue<Integer> que1; Queue<Integer> que2; public MyStack() { que1 = new LinkedList<>(); que2 = new LinkedList<>(); } public void push(int x) { que2.offer(x); while(!que1.isEmpty())//que1不为空 { //把que1的元素转移到que2后面 que2.offer(que1.poll()); } //然后交换两个队列的值,这样弹出和删除操作就直接使用que1就可以了 Queue<Integer> temp; temp=que1; que1=que2; que2=temp; } public int pop() { return que1.poll(); } public int top() { return que1.peek(); } public boolean empty() { return que1.isEmpty(); } } /** * Your MyStack object will be instantiated and called as such: * MyStack obj = new MyStack(); * obj.push(x); * int param_2 = obj.pop(); * int param_3 = obj.top(); * boolean param_4 = obj.empty(); */
有效的括号
正解:
括号不匹配只有三种情况:左侧多/少--数量正确,类型不符--右侧多/少
class Solution { public boolean isValid(String s) { Deque<Character> deque=new LinkedList<>(); char ch; for(int i=0;i<s.length();i++){ ch=s.charAt(i); //取出每一个符号,判断是不是规定的符号,是, 则在栈中存储与之对应的右括号, if(ch=='('){ deque.push(')'); }else if(ch=='{'){ deque.push('}'); }else if(ch=='['){ deque.push(']'); }else if(deque.isEmpty()|| deque.peek()!=ch){ //栈空了[右边括号多了],或者不满足匹配,结束循环 return false; }else{ deque.pop();//满足匹配,就出栈 } } //判断栈是否为空,满足则true return deque.isEmpty(); } }
删除字符串中的所有相邻重复项
正解:
class Solution { public String removeDuplicates(String s) { //创建栈 ArrayDeque<Character> ad=new ArrayDeque<>(); char ch; for(int i=0;i<s.length();i++){ ch=s.charAt(i); if(ad.isEmpty()||ad.peek()!=ch){ ad.push(ch); }else{ ad.pop(); } } String res=""; //这里做翻转操作 while(!ad.isEmpty()){ res=ad.pop()+res; } return res; } }
逆波兰表达式求值
正解:
class Solution { public int evalRPN(String[] tokens) { Deque<Integer> stack=new LinkedList<>(); for(String s:tokens){ if("+".equals(s)){ stack.push(stack.pop()+stack.pop()); }else if("-".equals(s)){ stack.push(-stack.pop()+stack.pop());//之所以是这么写,是因为要满足出栈后的计算表达式也和原来的数组里面的顺序一致,不然结果就不一样了 }else if("*".equals(s)){ stack.push(stack.pop()*stack.pop()); }else if("/".equals(s)){ int n1=stack.pop(),n2=stack.pop(); stack.push(n2/n1);//之所以是这么写,是因为要满足出栈后的计算表达式也和原来的数组里面的顺序一致,不然结果就不一样了 }else{ stack.push(Integer.valueOf(s)); } } return stack.pop(); } }