Title: Enter a sequence of two integers. One of the sequences represents the push order of the stack, judging whether another sequence is likely to be the corresponding pop order.
For the sake of simplicity, we assume that any two integers of the push sequence are not equal.
For example, the input push sequence is 1, 2, 3, 4, 5, then 4, 5, 3, 2, 1 may be a pop series, but the sequence 4, 3, 5, 1, 2 can not be the push sequence 1, 2, 3, 4, 5 of the pop sequence.
Analysis:
We first define the ordinal of the traversal push i=0 the ordinal J =0 of the pop sequence.
We can first iterate over the given push sequence and compare it with the head element Pop[j] of the pop sequence at all times.
If you find a push element that is the same as the head element of a pop sequence, J moves one to the right (you need to compare pop[j when the move is complete) is not equal to the top element of the current stack, and you need to exit the current top element if it is equal)
If the push has been traversed, but J is still less than the number of elements in the pop, then we just need to continue comparing the remaining elements in the pop with the elements in the current stack.
Code:
Func Judgestackorder (var pusharray:array<Int;,var poparray:Array <Int>),Bool{
var tempstack = Stack<Int> ()//construct a tempstack temporary stack
if(Pusharray = = [] | | poparray = = []) {
return false
}
if(Pusharray. Count ! = Poparray. Count) {
return false
}
var i = 0, j = 0
for(i; i < Pusharray. Count ; i++) {
println(i)
if(pusharray[i]! = Poparray[j]) {
println(pusharray[i])
Tempstack. push(Pusharray[i])
}
else{
Tempstack. push(Pusharray[i])
Tempstack. pop()
if(tempstack. Top() = = poparray[j+1]) {
Tempstack. pop()
J + +
}
J + +
}
}
if(J < Poparray. Count) {
while(J < Poparray. Count ) {
if(tempstack. Top()! = Poparray[j]) {
println(tempstack. Top())
POPARRAY[J]
return false
}
else{
Tempstack. pop()
J + +
Continue//If the current stack top element is equal to the element of the pop sequence at which J is present, the temporary stack is retired and the J moves to the right one unit, jumping into the next round of loops
}
}
return true
}
return false
}
Test code
var pusharray:Array<Int> = [1,3,5,7,9 ,8]
var poparray:Array<Int> = [3,1,9,8,7, 5]
Judgestackorder(pusharray, poparray)
Swift handles stack problems-given two sets of sequences, one of which represents the push order of the stack, and whether another sequence is likely to be the corresponding pop order