題目描述
輸入兩個整數序列,第一個序清單示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
思路:
周遊待測試序列,如果目前元素在棧頂,出棧即可,否則,檢視是否所有待入棧元素已入棧,如是說明目前元素在棧裡面但又不在棧頂,顯然出棧順序錯誤,若沒入棧,則按順序從待入棧集合中入棧直到棧頂元素是目前元素,出棧…
Java AC代碼:
import java.util.Stack;
public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
//pushA或者popA為null,傳回false
if (pushA == null || popA == null){
return false;
}
int m = pushA.length;
int n = popA.length;
Stack<Integer> stack = new Stack<>();
//pushA或者popA裡沒有元素,傳回false
if ( m == 0 || n == 0){
return false;
}
int start = 0;
for(int i = 0 ; i < n ; i++){
//如果棧頂元素與出棧元素不等,檢視是否所有待入棧元素已入棧
while(stack.isEmpty() ||stack.peek() != popA[i]){
if ( start >= m){
return false;
}
stack.push(pushA[start++]);
}
//如是說明目前元素在棧裡面但又不在棧頂,顯然出棧順序錯誤
if ( stack.peek() != popA[i]){
return false;
}
stack.pop();
}
return true;
}
}
複制
C++ AC代碼
class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
int m = pushV.size();
int n = popV.size();
if(m == 0 || n == 0){
return false;
}
stack<int> s;
int start = 0;
for(int i = 0 ; i < m ; i++){
while(s.empty() || s.top() != popV[i]){
if(start >= m){
return false;
}
s.push(pushV[start++]);
}
if(s.top() != popV[i]){
return false;
}
s.pop();
}
return true;
}
};
複制