public boolean validateStackSequences(int[] pushed, int[] popped) { int m = pushed.length; int n = popped.length; if(m!=n) return false; if(m == 1) return pushed[0] == popped[0]; Stack<Integer> stack = new Stack<>(); int i = 0,j = 0; while(j<n){ if(i<m && stack.isEmpty()){ stack.push(pushed[i++]); } if(!stack.isEmpty() && popped[j] == stack.peek()){ stack.pop(); j++; }else{ if(i<m) { stack.push(pushed[i++]); }else{ return false; } } } return stack.isEmpty() && j == n; }
方法二:
多妙的方法啊,我还达不到这个水平
public boolean validateStackSequences(int[] pushed, int[] popped) { int push=-1; int pop=0; for(int i=0;i<pushed.length;i++){ push++; pushed[push]=pushed[i]; if(pushed[i]==popped[pop]){ while(push>-1&&pushed[push]==popped[pop]){ push--; pop++; } } } return pop==popped.length; }