栈的压入弹出序列_JAVA_中等

栈的压入、弹出序列

http://www.nowcoder.com/questionTerminal/d77d11405cc7470d82554cb392585106

  • 每次压完栈之后,就可能匹配出栈,如果可以出栈,就一直出栈直到为空
  • 如果最后一次压栈出栈之后,栈还不为空,则不匹配

一开始的代码:

import java.util.*;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        int in = 0, out = 0;
        Stack<Integer> stack = new Stack();
        while(in < pushA.length || !stack.empty()) {
            // 压栈
            if(stack.empty() || stack.peek() != popA[out]) {
                if(in == pushA.length) {
                    break;
                }
                stack.push(pushA[in++]);
            // 出栈
            } else {
                stack.pop();
                out++;
            }
        }
        return stack.empty();
    }
}

优化后的代码:

import java.util.*;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        int in = 0, out = 0;
        Stack<Integer> stack = new Stack();
        while(in < pushA.length) {
            // 压栈
            stack.push(pushA[in++]);
            // 出栈
            while(!stack.empty() && stack.peek() == popA[out]) {
                out++;
                stack.pop();
            }
        }
        return stack.empty();
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务