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

来源:互联网 发布:java入门到精通 4 pdf 编辑:程序博客网 时间:2024/06/05 02:09

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列。假设压入栈的所有数字均不相等。例如压栈序列为 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;    }}
原创粉丝点击