您的位置:首页 > Web前端

剑指offer 22. 栈的压入、弹出序列

2017-05-09 16:38 281 查看
// 题目:输入两个整型数组,判断第二个是不是第一个的栈输出序列
// 解法:使用队列完成,输出传入栈中再输出
public class Main {

public static void main(String[] args) {

System.out.println(isSeq(new int[] { 1, 2,3,4,5 }, new int[] {4,5,3,2,1 }));
}

private static boolean isSeq(int[] input, int[] output) {
if(input.length == 0 || input.length != output.length){								//如果长度不相等,直接false
return false;
}
Stack<Integer> s = new Stack<Integer>();						//建立栈,模拟实际情况
int inputIndex = 0;
int outputIndex = 0;
while(outputIndex != output.length){							//如果输出队列没有遍历完
if(inputIndex == input.length && s.peek()!= output[outputIndex]){			//如果输入队列遍历完了且栈顶元素不为输入的当前元素就false
return false;
}
while(s.isEmpty() || s.peek()!=output[outputIndex]){						//如果栈为空或栈顶元素不为输出队列的当前元素就将输入队列的元素入栈
s.push(input[inputIndex++]);
if(inputIndex == input.length && s.peek()!= output[outputIndex]){
return false;
}
}
s.pop();													//如果相同就出栈并检查输出序列的下一个元素
outputIndex++;
}
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: