Skip to content

[剑指 Offer] 31. 栈的压入、弹出序列 #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Aug 1, 2021 · 0 comments
Open

[剑指 Offer] 31. 栈的压入、弹出序列 #61

frdmu opened this issue Aug 1, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Aug 1, 2021

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如,序列 {1,2,3,4,5} 是某栈的压栈序列,序列 {4,5,3,2,1} 是该压栈序列对应的一个弹出序列,但 {4,3,5,1,2} 就不可能是该压栈序列的弹出序列。

 

示例 1:

输入:pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
输出:true
解释:我们可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1

示例 2:

输入:pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
输出:false
解释:1 不能在 2 之前弹出。

提示:

  • 0 <= pushed.length == popped.length <= 1000
  • 0 <= pushed[i], popped[i] < 1000
  • pushed 是 popped 的排列。


解法:
模拟栈,遍历入栈数组,每压入一个元素,判断其是否能弹出。若栈最后为空,则true。代码如下:

class Solution {
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
        stack<int> stk;
        int n = pushed.size();
        int p = 0, q = 0; 

        while (p < n) {
            stk.push(pushed[p++]);
            while (!stk.empty() && stk.top() == popped[q]) {
                stk.pop();
                q++;
            }
        }
        
        if (stk.empty()) 
            return true;
        return false;    
    }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant