栈
两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if(stack2.size()<=0){//如果第二个栈为空才往里面push; while(!stack1.isEmpty()){ stack2.push(stack1.pop()); }} int head = stack2.pop(); // while(!stack2.isEmpty()){ // stack1.push(stack2.pop()); // }//我的方法在连续pop时将很浪费时间; return head; } }
括号匹配
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列
括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
import java.util.*; import java.util.Stack; public class Solution { /** * * @param s string字符串 * @return bool布尔型 */ public boolean isValid (String s) { // write code here Stack<Character> c = new Stack<Character>(); for(int i = 0 ; i < s.length(); i++){ if(c.empty()){//为空就入栈 c.push(s.charAt(i)); continue; }//否则比较栈顶。匹配才出栈 if(s.charAt(i)==')'&&c.peek()=='('){c.pop();} else if(s.charAt(i)=='}'&&c.peek()=='{'){c.pop();} else if(s.charAt(i)==']'&&c.peek()=='['){c.pop();} else{ c.push(s.charAt(i));}//不为空要入栈时在最后处理 } return c.empty(); } }