CleanCodeHandbook Chapter 7: Stack(39-41)

Stack

leetcode155. Min Stack

题目链接
题目:设计一个支持 push,pop,top 操作,并能在常数时间内检索到最小元素的栈。

push(x) – 将元素 x 推入栈中。
pop() – 删除栈顶的元素。
top() – 获取栈顶元素。
getMin() – 检索栈中的最小元素。
示例:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
思路:设计两个栈,一个存放数字,一个存放最小值,需要注意的是 在最小值栈为空或者当前入栈元素比最小值栈顶元素小的时候,不但需要压如数字栈,而且要进最小值栈;在出栈的时候,如果出栈元素等于最小值栈顶元素,则最小值栈栈顶元素也要出栈。

class MinStack {

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> minStack = new Stack<>();
    /** initialize your data structure here. */
    public MinStack() {
        
    }
    
    public void push(int x) {
        stack.push(x);
        if(minStack.isEmpty() || x <= minStack.peek()){
            minStack.push(x);
        }
    }
    
    public void pop() {
        int x = stack.pop();
        if(x == minStack.peek()){
            minStack.pop();
        }
    }
    
    public int top() {
        return stack.peek();
    }
    
    public int getMin() {
        return minStack.peek();
    }
}

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

leetcode150. Evaluate Reverse Polish Notation

题目链接
题目:根据逆波兰表示法,求表达式的值。

有效的运算符包括 +, -, *, / 。每个运算对象可以是整数,也可以是另一个逆波兰表达式。

说明:

整数除法只保留整数部分。
给定逆波兰表达式总是有效的。换句话说,表达式总会得出有效数值且不存在除数为 0 的情况。
示例 1:

输入: [“2”, “1”, “+”, “3”, “*”]
输出: 9
解释: ((2 + 1) * 3) = 9
示例 2:

输入: [“4”, “13”, “5”, “/”, “+”]
输出: 6
解释: (4 + (13 / 5)) = 6
示例 3:

输入: [“10”, “6”, “9”, “3”, “+”, “-11”, “", “/”, "”, “17”, “+”, “5”, “+”]
输出: 22
解释:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
题目思路:利用两个栈,一个存放数字,一个存放符号,当符号栈不为空的时候,符号出栈,并且数字栈出来俩数,进行计算,并把计算完的结果入数字栈,最后返回数字栈的最后一个数字即可(当然最后数字栈中也只有一个数字)。

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        Stack<String> stack_ch = new Stack<>();
        String op = "+-/*";
        int x, y;
        for(String s : tokens){
            if(op.contains(s)){
                stack_ch.push(s);
            }else{
                stack.push(Integer.parseInt(s));
            }
            while(!stack_ch.isEmpty()){
                y = stack.pop();
                x = stack.pop();
                switch(stack_ch.pop()){
                    case "+":stack.push(x + y);break;
                    case "-":stack.push(x - y);break;
                    case "*":stack.push(x * y);break;
                    case "/":stack.push(x / y);break;
                }
            }
        }
        return stack.pop();
    }
}

有一种代码叫别人的代码,,,思路基本一样,就是写的代码确实漂亮:

class Solution {
    private final Set<String> OPERATORS = new HashSet<>(Arrays.asList("+", "-", "*", "/"));
    private int eval(int x, int y, String operator) {
        switch (operator) {
            case "+": return x + y;
            case "-": return x - y;
            case "*": return x * y;
            default: return x / y;
        }
    }
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        int x, y;
        for(String token : tokens){
            if(OPERATORS.contains(token)){
                y = stack.pop();
                x = stack.pop();
                stack.push(eval(x, y, token));
            }else{
                stack.push(Integer.parseInt(token));
            }
        }
        return stack.pop();
    }   
}

使用接口,使代码更具有扩展性:

class Solution {
    interface Operator {
        int eval(int x, int y);
    }
    private static final Map<String, Operator> OPERATORS = new HashMap<String, Operator>() {
        {
            put("+", new Operator() {
                public int eval(int x, int y) { return x + y; }
            });
            put("-", new Operator() {
                public int eval(int x, int y) { return x - y; }
            });
            put("*", new Operator() {
                public int eval(int x, int y) { return x * y; }
            });
            put("/", new Operator() {
                public int eval(int x, int y) { return x / y; }
            });
        }
    };
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        for (String token : tokens) {
            if (OPERATORS.containsKey(token)) {
                int y = stack.pop();
                int x = stack.pop();
                stack.push(OPERATORS.get(token).eval(x, y));
            } else {
                stack.push(Integer.parseInt(token));
            }
        } 
        return stack.pop();
    }
}

leetcode20. Valid Parentheses

题目链接
题目描述:给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。

示例 1:

输入: “()”
输出: true
示例 2:

输入: “()[]{}”
输出: true
示例 3:

输入: “(]”
输出: false
示例 4:

输入: “([)]”
输出: false
示例 5:

输入: “{[]}”
输出: true
思路:括号匹配,如果是左括号,则入栈,若是右括号,则查看栈是否为空,若为空返回false,若栈不为空,则弹出栈顶元素,并与该右括号进行匹配,如果不匹配返回false。最后 查看栈是否为空即可。

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        String value = "})]";
        for(char ch : s.toCharArray()){
            if(stack.isEmpty() && value.contains(Character.toString(ch))){
                return false;
            }
            switch(ch){
                case '}':if(stack.peek() == '{'){ stack.pop();}else{stack.push(ch);}break;
                case ')':if(stack.peek() == '('){ stack.pop();}else{stack.push(ch);}break;
                case ']':if(stack.peek() == '['){ stack.pop();}else{stack.push(ch);}break;
                default:stack.push(ch);break;
            }
        }
        return stack.isEmpty();
    }
}

别人的代码:

class Solution {
    private static final Map<Character, Character> map = new HashMap<Character,Character>() {{
    put('(', ')');
    put('{', '}');
    put('[', ']');
    }};
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(char ch : s.toCharArray()){
            if(map.containsKey(ch)){
                stack.push(ch);
            }else if(stack.isEmpty() || ch != map.get(stack.pop())){
                    return false;
            }
        }
        return stack.isEmpty();
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值