NC272. 栈的压入、弹出序列
描述
示例1
输入:
[1,2,3,4,5],[4,5,3,2,1]
输出:
true
说明:
可以通过push(1)=>push(2)=>push(3)=>push(4)=>pop()=>push(5)=>pop()=>pop()=>pop()=>pop() 这样的顺序得到[4,5,3,2,1]这个序列,返回true示例2
输入:
[1,2,3,4,5],[4,3,5,1,2]
输出:
false
说明:
由于是[1,2,3,4,5]的压入顺序,[4,3,5,1,2]的弹出顺序,要求4,3,5必须在1,2前压入,且1,2不能弹出,但是这样压入的顺序,1又不能在2之前弹出,所以无法形成的,返回falseRust 解法, 执行用时: 2ms, 内存消耗: 424KB, 提交时间: 2021-07-23
struct Solution{ } impl Solution { fn new() -> Self { Solution{} } /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * @param pushV int整型一维数组 * @param popV int整型一维数组 * @return bool布尔型 */ pub fn IsPopOrder(&self, pushV: Vec<i32>, popV: Vec<i32>) -> bool { // write code here if pushV.len() != popV.len() { return false; } let mut help:Vec<i32> = vec![]; let mut pop_v = popV; pop_v.reverse(); for item in pushV { help.push(item); loop { match help.pop().take() { Some(cur) => { if let Some(pop_node) = pop_v.pop().take() { if pop_node != cur { pop_v.push(pop_node); help.push(cur); break; } } else { return false; } }, None => { break; } } } } help.is_empty() } }
C++ 解法, 执行用时: 2ms, 内存消耗: 556KB, 提交时间: 2022-02-10
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { int size = pushV.size(); stack<int> stk; int j = 0; for(int i = 0; i < size; ++i){ while(j < size && (stk.empty() || stk.top() != popV[i])){ stk.push(pushV[j]); ++j; } if(stk.top() == popV[i]){ stk.pop(); } else { return false; } } return true; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 556KB, 提交时间: 2021-10-31
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { stack<int> st; int pushi = 0; int popi = 0; while (pushi < pushV.size()) { st.push(pushV[pushi]); ++pushi; while (!st.empty() && st.top() == popV[popi]) { st.pop(); ++popi; } } return st.empty(); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 560KB, 提交时间: 2021-11-18
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { stack<int> st; int i = 0, j = 0; while(i < pushV.size()){ if(pushV[i] == popV[j]){ ++i; ++j; while(!st.empty() && popV[j]==st.top()){ st.pop(); ++j; } }else{ st.push(pushV[i++]); } } return st.empty(); } };
C++ 解法, 执行用时: 2ms, 内存消耗: 592KB, 提交时间: 2022-02-10
class Solution { public: bool IsPopOrder(vector<int> pushV,vector<int> popV) { stack<int>stack1; int j = 0; for(int i = 0;i < pushV.size();i++) { stack1.push(pushV[i]); while(!stack1.empty() && popV[j] == stack1.top()) { stack1.pop(); j++; } } if(stack1.empty()) return true; else return false; } };