方法一:根据出栈顺序判断
比当前出栈值小的,一定是递减的(必须保证入栈顺序递增)
public boolean validateStackSequences(int[] pushed, int[] popped) {
if(popped.length == 0) return true;
int max = popped[0];
for(int i=1; i<popped.length; i++){
if(popped[i-1] < popped[i] && popped[i] < max)
return false;
max = Math.max(Math.max(popped[i-1], popped[i]), max);
}
return true;
}方法二:模拟栈进出判断
public boolean validateStackSequences(int[] pushed, int[] popped) {
Stack<Integer> stack = new Stack<Integer>();
for(int i=0, j=0; i<pushed.length; i++){
stack.push(pushed[i]);
while(!stack.isEmpty() && stack.peek() == popped[j]){
stack.pop();
j++;
}
}
return stack.isEmpty();
}版权声明:本文为xiayinggudeng原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。