代码随想录算法训练营第十一天 | 20、150、1047

20. Valid Parentheses

题目链接:https://leetcode.cn/problems/valid-parentheses/

2 代码实现

class Solution {
        public boolean isValid(String s) {
                Stack<Character> deque = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);

            if (ch == '('){
                deque.push(')');
            }else if (ch == '{'){
                deque.push('}');
            }else if (ch == '['){
                deque.push(']');
            }else if (deque.isEmpty() || deque.peek() != ch){
                return false;
            }else {
                //deque.pollFirst();
                deque.pop();
            }

        }
        return deque.isEmpty();
    }
}

150. Evaluate Reverse Polish Notation

题目链接:https://leetcode.cn/problems/evaluate-reverse-polish-notation/

方法一

1 方法思想

2 代码实现

class Solution {
    public static int evalRPN(String[] tokens) {
       Stack<Integer> stack  = new Stack<>();

        stack.push(Integer.valueOf(tokens[0]));
        for (int i = 1; i < tokens.length; i++) {
            String ch = tokens[i];
            if (ch.equals("+")){
                int temp = stack.pop();
                stack.push(stack.pop() + temp);
            }else if (ch.equals("-")){
                int temp = stack.pop();
                stack.push(stack.pop() - temp);
            }else if (ch.equals("*")){
                int temp = stack.pop();
                stack.push(stack.pop() * temp);
            }else if (ch.equals("/")){
                int temp = stack.pop();
                stack.push(stack.pop() / temp);
            }else {
                stack.push(Integer.valueOf(ch));
            }

        }

        return stack.pop();


    }
}

3 复杂度分析

时间复杂度:
空间复杂度:

4 涉及到知识点

方法二

1 方法思想

2 代码实现

1047. Remove All Adjacent Duplicates In String

题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/

2 代码实现

class Solution {
        public String removeDuplicates(String s) {
        Deque<Character> deque = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (!deque.isEmpty() && ch == deque.getLast()) {
                deque.removeLast();
            } else {
                deque.addLast(ch);
            }
        }
        //StringBuilder ans = new StringBuilder();
        //while (deque.isEmpty()) {
        //    ans.append(deque.pollFirst();
        //}
        String ans = "";
        while (!deque.isEmpty()){
            ans+=deque.pollFirst();
        }
        //return new String(ans);
        return ans;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值