LeetCode(剑指 Offer)- 31. 栈的压入弹出序列

Posted 放羊的牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(剑指 Offer)- 31. 栈的压入弹出序列相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:

解题思路:

相关企业

  • 4399
  • 字节跳动

AC 代码

  • Java
// 解决方案(1)
class Solution 
    public boolean validateStackSequences(int[] pushed, int[] popped) 
		int[] stack = new int[pushed.length];
		for (int i = 0, j = 0, top = -1; i < popped.length; i++) 
			boolean flag = false;
			int pop = popped[i];
			if (top != -1 && stack[top] == pop) 
				top--;
				flag = true;
			 else 
				while (j < pushed.length) 
					if (pushed[j] == pop) 
						j++;
						flag = true;
						break;
					
					stack[++top] = pushed[j++];
				
			

			if (!flag) 
				return false;
			
		
		return true;
	


// 解决方案(2)
class Solution 
    public boolean validateStackSequences(int[] pushed, int[] popped) 
        Stack<Integer> stack = new Stack<>();
        int i = 0;
        for(int num : pushed) 
            stack.push(num); // num 入栈
            while(!stack.isEmpty() && stack.peek() == popped[i])  // 循环判断与出栈
                stack.pop();
                i++;
            
        
        return stack.isEmpty();
    
  • C++
class Solution 
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) 
        stack<int> stk;
        int i = 0;
        for(int num : pushed) 
            stk.push(num); // num 入栈
            while(!stk.empty() && stk.top() == popped[i])  // 循环判断与出栈
                stk.pop();
                i++;
            
        
        return stk.empty();
    
;

以上是关于LeetCode(剑指 Offer)- 31. 栈的压入弹出序列的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 剑指 Offer 09. 用两个栈实现队列 | Python

[LeetCode]剑指 Offer 09. 用两个栈实现队列

LeetCode(剑指 Offer)- 09. 用两个栈实现队列

LeetCode剑指 Offer 09. 用两个栈实现队列

[leetcode]剑指 Offer 09. 用两个栈实现队列

leetcode剑指 Offer 09. 用两个栈实现队列