LintCode 377: Stack Push-Pop Sequence (Stack 好题)

  1. Stack Push-Pop Sequence
    中文English
    Given a push sequence and pop sequence of a stack. Decide whether there are legal sequences.

Example
Example 1:

Input: push = [1, 2, 3], pop = [3, 2, 1]
Output: True
Explanation: Push 1, 2, 3 and pop 3, 2, 1.
Example 2:

Input: push = [1, 2, 3], pop = [3, 1, 2]
Output: False
Explanation:
If we want to first pop 3, the 1 and 2 must already in the stack, and 2 is on the top of 1, in this situation, 1 can not be popped before 2.
Notice
The number of elements does not exceed 1000

解法1:
用一个stack,挨个将push序列push到stack中。用一个指针pointer指向pop序列的最开头。每次push后看1)stack是否为空;2) 若非空则看stack的top元素是否和pop序列的pointer指向元素相等。若相等,则pop出该top元素,并将pointer元素后移。该操作不断循环,直到stack为空或stack的top元素与pop序列的pointer指向元素不相等。然后再将push序列的下一个元素push到stack中。
最后如果stack为空,则为合法pop序列,否则为非法。

代码如下:

class Solution {
public:
    /**
     * @param push: the array push
     * @param pop: the array pop
     * @return: return whether there are legal sequences
     */
    bool isLegalSeq(vector<int> &push, vector<int> &pop) {
        int m = push.size();
        int n = pop.size();
        if (m != n) return false;
        if (n == 0) return true;
        
        stack<int> st;
		int index = 0;   // index is for arr, num is from [1,2,3,...]
		for (int i = 0; i < n; ++i) {
            st.push(push[i]);
		    while(!st.empty() && st.top() == pop[index]) {
		       st.pop();
			   index++;
		    }
		}
		
		if (!st.empty()) return false;

		return true;
    }
};

解法2:TBD

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值