面试题22. 栈的压入、弹出序列
来源:互联网 发布:unity3d 点光源不亮 编辑:程序博客网 时间:2024/06/05 07:59
题目描述
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列【1、2、3、4、5】是某栈的压入顺序,序列【4、5、3、2、1】是该压栈序列对应的一个弹出序列,但【4、3、5、1、2】就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:
用一个辅助栈,按照入栈的顺序,向辅助栈中添加元素,如果栈顶与出栈元素相同,则出栈。最后判断辅助栈是否为空即可。
如图所示,最后栈为空,说明【4、5、3、2、1】是【1、2、3、4、5】的出栈顺序。
java 代码:
import java.util.ArrayList;import java.util.Stack;public class Solution { public boolean IsPopOrder(int [] pushA, int [] popA) { int pushLen = pushA.length; int popLen = popA.length; if( pushLen != popLen || pushLen == 0) { return false; } Stack<Integer> _stack = new Stack<>(); int index = 0; for(int i = 0; i < pushLen; i++) { _stack.push(pushA[i]); while(!_stack.empty() && _stack.peek() == popA[index]) { _stack.pop(); index++; } } return _stack.empty(); }}
python代码:
# -*- coding:utf-8 -*-class Solution: def IsPopOrder(self, pushV, popV): stack = [] if len(pushV) != len(popV) or len(pushV) == 0: return False index = 0 for i in pushV: stack.append(i) while len(stack) > 0 and stack[-1] == popV[index]: stack.pop() index += 1 return len(stack) == 0
阅读全文
0 0
- 面试题22. 栈的压入、弹出序列
- 面试题20:栈的压入、弹出序列
- 【面试题二十二】栈的压入、弹出序列
- 面试题整理6 栈的压入、弹出序列
- 栈的压入、弹出序列(面试题 22)
- 面试题22:栈的压入弹出序列
- 面试题22栈的压入、弹出序列
- 面试题22 栈的压入弹出序列
- 面试题22:栈的压入弹出序列
- 面试题22:栈的压入、弹出序列
- 【经典面试题】栈的压入弹出序列
- 面试题26:栈的压入、弹出序列
- 栈的压入、弹出序列(剑指offer面试题)
- 剑指offer面试题 栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22 栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 查看Android签名
- qwb与矩阵 【DP】+【输入挂】
- iostream整理
- LeetCode532. K-diff Pairs in an Array
- 集群中配置多台计算机之间ssh无密码登录的一种简便方法
- 面试题22. 栈的压入、弹出序列
- linux使用常识
- leetcode Add to List 200. Number of Islands
- EasyUI Datagrid中load,reload,loadData的区别。
- 该把JS文件放在HTML文档的那个位置
- Win 下 Java 环境变量配置
- tp的复合查询
- Android 反编译 -smali语法
- 网络安全重点总结1