diff --git a/README.md b/README.md index a87edaf..924f5dd 100644 --- a/README.md +++ b/README.md @@ -293,3 +293,4 @@ My LeetCode solutions with Chinese explanation. 我的LeetCode中文题解。 | 665 |[Non-decreasing Array](https://leetcode.com/problems/non-decreasing-array)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/665.%20Non-decreasing%20Array.md)|Easy| | | 714 |[Best Time to Buy and Sell Stock with Transaction Fee](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/)|[C++](https://github.com/ShusenTang/LeetCode/blob/master/solutions/714.%20Best%20Time%20to%20Buy%20and%20Sell%20Stock%20with%20Transaction%20Fee.md)|Medium| | | 905 |[Sort Array By Parity](https://leetcode.com/problems/sort-array-by-parity/)|[C++](solutions/905.%20Sort%20Array%20By%20Parity.md)|Easy| | +| 946 |[Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/)|[C++](solutions/946.%20Validate%20Stack%20Sequences.md)|Medium| | diff --git a/solutions/946. Validate Stack Sequences.md b/solutions/946. Validate Stack Sequences.md new file mode 100644 index 0000000..68b0146 --- /dev/null +++ b/solutions/946. Validate Stack Sequences.md @@ -0,0 +1,78 @@ +# [946. Validate Stack Sequences](https://leetcode.com/problems/validate-stack-sequences/) + +# 思路 + +输入两个整数序列,第一个序列表示栈的入栈顺序,请判断第二个序列是否可能为该栈的出栈顺序。 + +## 思路一 + +例 +``` +pushed = [1,2,3,4,5] +popped = [4,5,3,2,1] +``` +出栈序列第一个是4,我们要什么时候pop出4呢,很明显是当4第一次出现在栈顶的时候(即push了4就要立马pop出),否则为了pop出4需要先pop出在4上面的元素,不符合出栈序列要求。出栈序列后面的元素同理,即是一个**贪心**的过程: 从前往后依次将元素入栈,在这个过程中不断判断栈顶元素是否为下一个popped元素,若是则应该出栈。最后如果栈为空则说明全部出栈了,返回真;否则返回假。 + +时空复杂度均为O(n) + +## 思路二 + +一开始想到的是暴力法,即模拟出入栈的过程,用DFS回溯。亲测比思路一慢很多很多,就不细说了。 + +# C++ + +## 思路一 +``` C++ +class Solution { +public: + bool validateStackSequences(vector& pushed, vector& popped) { + int n = pushed.size(), pop_i = 0; + stackstk; + for(int i = 0; i < n; i++){ + stk.push(pushed[i]); + while(!stk.empty() && stk.top() == popped[pop_i]){ + stk.pop(); + pop_i++; + } + } + return stk.empty(); + } +}; +``` + +## 思路二 +``` C++ +class Solution { +private: + vectorpushed_, popped_; + int n; + bool helper(stack&stk, int push_i, int pop_i){ + if(pop_i == n) return true; + + // 出栈 + if(!stk.empty() && stk.top() == popped_[pop_i]){ + int tmp = stk.top(); stk.pop(); + if(helper(stk, push_i, pop_i + 1)) return true; + stk.push(tmp); + } + + // 入栈 + if(push_i >= n) return false; + stk.push(pushed_[push_i]); + if(helper(stk, push_i + 1, pop_i)) return true; + + return false; + } +public: + bool validateStackSequences(vector& pushed, vector& popped) { + pushed_ = pushed; + popped_ = popped; + n = pushed.size(); + if(n <= 1) return true; + stackstk, out; + int i = 0; + return helper(stk, 0, 0); + } +}; +``` +