剑指Offer: (Java实现) 栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数字均不相等。例如压栈序列为 1、2、3、4、5.序列 4、5、3、2、1 是压栈序列对应的一个弹出序列,但 4、3、5、1、2 却不是。


分析:学过数据结构的人都知道,这种判断是考试中必考的。现在用Java语言实现,无非就是将逻辑转化为代码。假设大家知道 某个序列能否从特定的入栈顺序的组成的栈中弹出的规则。

import java.util.Stack;

/**
 * @author 作者 : shanzhi
 * @version 创建时间:2017-5-28 下午12:19:33
 * 贡献点在于用Java来实现
 */
public class JZ22_StackInputOuput {
    public static int sL = 0;
    public static int oL = 0;
    public static void main(String[] args) {
        int[] source = {1,2,3,4,5};
        int[] out1 = {4,5,3,2,1};
        int[] out2 = {4,3,5,1,2};
        sL = source.length;  
        oL = out1.length;
        System.out.println(match(source,out1));
    }
    public static boolean match(int[] source,int[] out){
        int i = 0;
        Stack<Integer> sta = new Stack<Integer>();
        int index1 = 0;  //对应source的下标,用于获取具体值
        int index2 = 0;  //对应out的下标,用于获取具体值
        while( index2 < oL){
            int r1 = findIndex(source,out[index2]);
            if( r1 == sL){
                break;
            }else if( r1 >= index1 ){
                for ( i = index1;i <= r1;i++){
                    sta.push(source[i]);
                }
                index1 = i;
                sta.pop();
                index2++;
            }else if( r1 < index1 ){
                if( sta.peek() != out[index2]){
                    break;
                } else {
                    sta.pop();
                    index2++;
                }
            }   
        }
        if( index2 == oL ){
            return true;
        }
        return false;
    }
    /**
     * 如果返回的是source数组的长度说明没找到。
     */
    public static int findIndex(int[] source, int num){
        int i = 0;
        for( ; i< sL; i++){
            if( source[i] == num){
                break;
            }
        }
        return i;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值