Leetcode stackAquene stack push and pop sequence

THE

problem

Insert picture description here

solution

Code

/*
思路: 这道题一开始我都看不懂。。。不知道找什么。看了一下分析才发现, 这道题的输入中间是可以穿插输出的。
那么整体的思路就是压入的时候判断是否等于输出的第一个了, 如果等于的话代表这个被弹出了,然后继续压入判断。

- 
- 
- - 
- - 
- 
*/

class Solution {
    
    
public:
   bool IsPopOrder(vector<int> pushV,vector<int> popV) {
    
    
       if(pushV.size()!= popV.size()) return false;
       stack<int> in ;
       
       int j = 0;
       for(int i = 0; i<pushV.size();i++){
    
    
           if(pushV[i]!=popV[j])in.push(pushV[i]);
           else {
    
    
               
               ++j;
               while((!in.empty())&&(in.top()==popV[j])){
    
    
                   in.pop();
                   ++j;
               }                    
           }
       }
       return in.empty();
       
       
   }
};


Summary and reflection

  1. // Note while(!in.empty())&&(in.top()==popV[j]) and while((in.top()==popV[j])&&(!in.empty() ) The difference. The first judgment is empty and exit, but if you put j to the front, it will cause out of bounds. The logic is okay, but it is indeed out of bounds. You need to pay attention to the design in the future.

Guess you like

Origin blog.csdn.net/liupeng19970119/article/details/114259209