42. The stack push, pop sequence

 

 

This problem as long as the test center on problem-solving ideas:

Links: https://www.nowcoder.com/questionTerminal/d77d11405cc7470d82554cb392585106?f=discussion
Source: Cattle-off network

Borrow an auxiliary stack, push traversal order, into a first talk about the stack, here 1, is determined and then the top element is not out of the first element stack order, this is 4, it is clear that a ≠ 4 so we continue to push until after the start of an equal stack, the stack is an element, it will move back one, until the order is not equal to the stack, and so the cycle Yazhan order traversal is complete, if the auxiliary stack is not empty described sequence is not the sequence of pop pop stack.

For example:

Drawing 1,2,3,4,5

4,5,3,2,1 Stack (popup sequence)

1 into the first auxiliary stack, when the stack 1 ≠ 4, continued stack 2

At this time, the stack 2 ≠ 4, continue to stack 3

At this time, the stack 3 ≠ 4, 4 continue to stack

At this time, the stack 4 = 4, 4 from the stack (auxiliary stack pop 4), a pop-up sequence back, in this case 5, which auxiliary stack is 1,2,3

At this time, the stack 3 ≠ 5, 5 continue to push

5 = At ​​this point the stack 5, the stack 5, a pop-up sequence back, in this case the auxiliary stack 3 which is 2,3 ,,

….

Followed by the implementation, and finally the auxiliary stack is empty. If not empty pop-described sequence is not the sequence of pop stack.

 

class Solution {
public:
    bool isPopOrder(vector<int> pushV,vector<int> popV) {
        stack<int> s;//辅助栈
        int index = 0;
        if(pushV.empty() && popV.empty()) return true;
        if(pushV.size() != popV.size())  return false;
        
        for(int i=0;i < pushV.size(); i++)
        {
            s.push(pushV[i]);
            //当满足while循环时,不会跳出去执行for循环,不会有新元素添加到s中
            //只有当while不满足时,才会有新元素添加到s中,继续执行while判断
            while(!s.empty() && s.top() == popV[index])
            {
                s.pop();
                index++;
            }
        }

        if(s.empty()) return true;
        return false;
    }
};

 

Guess you like

Origin www.cnblogs.com/make-big-money/p/12309458.html