博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
剑指Offer——栈的压入、弹出顺序
阅读量:4227 次
发布时间:2019-05-26

本文共 787 字,大约阅读时间需要 2 分钟。

题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

代码实现:

import java.util.ArrayList;import java.util.Stack;public class Solution {    //思路:用一个栈(s1)来模拟出栈的过程,这里用Stack来实现栈    //模拟过程:如果s1不为空,则看栈顶元素是否和出栈的第i个字符相等,如果相等    //就把栈顶元素出栈,比较新的栈顶元素和第i+1个元素;如果不等,那么按照入栈    //顺序将元素压栈,继续比较,如果元素已经全部压栈,但是s1中元素没有完成按顺    //序出栈,那么这个出栈顺序是不可能的    public boolean IsPopOrder(int [] pushA,int [] popA) {        Stack
s = new Stack<>(); for(int i = 0; i
=pushA.length && popIndex>= popA.length){ return true; } else if(pushIndex>=pushA.length && !s.isEmpty() && (s.peek() != popA[popIndex])){ return false; } } }}

转载地址:http://osnqi.baihongyu.com/

你可能感兴趣的文章
Using Samba
查看>>
XML Security
查看>>
Rails Cookbook
查看>>
Dynamic HTML: The Definitive Reference (Dynamic Html) [ILLUSTRATED]
查看>>
Python (Visual QuickStart Guide)
查看>>
Pro .NET 2.0 Windows Forms and Custom Controls in VB 2005
查看>>
RSA Security's Official Guide to Cryptography
查看>>
Artificial Intelligence for Games
查看>>
SQL Server 2005 Bible
查看>>
Distributed Systems Architecture: A Middleware Approach
查看>>
Beginning XML, 4th Edition
查看>>
Beginning JavaScript, 3rd Edition
查看>>
The TCP/IP Guide: A Comprehensive, Illustrated Internet Protocols Reference [ILLUSTRATED]
查看>>
Fault-Tolerant Systems
查看>>
C Programming for Scientists and Engineers
查看>>
Pragmatic Software Testing: Becoming an Effective and Efficient Test Professional
查看>>
Struts: The Complete Reference, 2nd Edition
查看>>
MCITP Developer: Microsoft SQL Server 2005 Database Solutions Design
查看>>
Text Entry Systems: Mobility, Accessibility, Universality
查看>>
CliffsTestPrep Cisco CCNA
查看>>