小渣渣的算法學習筆記:2018秋招備戰
資料結構類算法總結:棧
1.題目描述:
輸入兩個整數序列,第一個序清單示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。
假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,
序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,
但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
2.代碼實作:
public class Solution31 {
public static void main(String[] args) {
Solution31 s = new Solution31();
int []pusha = {1,2,3,4,5};
int []popa = {4,5,3,2,1};
boolean c = s.isPopOrder(pusha,popa);
System.out.println(c);
}
public boolean isPopOrder(int push[],int pop[]){
if(push.length == 0||pop.length == 0)
return false;
int index = 0;
Stack<Integer> s = new Stack<Integer>();
for(int i = 0;i<push.length;i++){
s.push(push[i]);
//輔助棧不為空and pop[i] == s.peek()
while(!s.empty()&&pop[index]==s.peek()){
s.pop();
index++;
}
}
return s.empty();
}
}