栈的压入弹出序列_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();
    }
}
全部评论

相关推荐

昨天 11:15
中南大学 Java
好可爱的hr姐姐哈哈哈哈
黑皮白袜臭脚体育生:兄弟们貂蝉在一起,吕布开了
点赞 评论 收藏
分享
认真搞学习:这么良心的老板真少见
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务