zoukankan      html  css  js  c++  java
  • 剑指offer31题

    题目描述

    输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
     
    模拟一个入栈操作,每次匹配即可。不想解释太多。直接看代码吧
    package com.algorithm04;
    
    import java.util.Stack;
    
    public class Algorithm31 {
    
    	public static boolean IsPopOrder(int [] pushA,int [] popA) {
    		Stack<Integer> stack = new Stack<Integer>();
    		int i , j ;
    		j = 0;
    		if(pushA.length==0 || popA.length == 0 || pushA.length!=popA.length){
    			return false;
    		}
    		for(i = 0 ; i< pushA.length ; i++){
    			stack.push(pushA[i]);
    			while(j < popA.length &&stack.peek()==popA[j]){
    				stack.pop();
    				j++;
    			}
    		}
    		return stack.size()==0?true:false;
        }
    	public static void main(String[] args) {
    		int [] pushA = {1,2,3,4,5};
    		int [] popA = {4,5,3,2,1};
     		System.err.println(IsPopOrder(pushA, popA));
    	}
    }
    

      

  • 相关阅读:
    转:PCIe基础知识
    转:HDMI介绍与流程
    Java EJB JBoss
    冒泡排序
    多线程
    快排
    Talk is cheap,show me the code
    oracle union
    Oracle 【to_number】【instr】
    DB 【ACID】
  • 原文地址:https://www.cnblogs.com/CloudStrife/p/7348426.html
Copyright © 2011-2022 走看看