代码随想录二刷day11

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣20. 有效的括号
  • 二、力扣1047. 删除字符串中的所有相邻重复项
  • 三、力扣150. 逆波兰表达式求值


前言


一、力扣20. 有效的括号

class Solution {
    public boolean isValid(String s) {
        Deque<Character> deq = new ArrayDeque<>();
        for(int i = 0; i < s.length(); i ++){
            if(s.charAt(i) == '(' || s.charAt(i) == '[' || s.charAt(i) == '{'){
                deq.offerLast(s.charAt(i));
            }else{
                if(deq.isEmpty()){
                    return false;
                }
                char temp = deq.pollLast();
                if(s.charAt(i) == ')' && temp != '('){
                    return false;
                }
                if(s.charAt(i) == ']' && temp != '['){
                    return false;
                }
                if(s.charAt(i) == '}' && temp != '{'){
                    return false;
                }
            }
        }
        return deq.isEmpty();
    }
}

二、力扣1047. 删除字符串中的所有相邻重复项

class Solution {
    public String removeDuplicates(String s) {
        Deque<Character> deq = new ArrayDeque<>();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < s.length(); i ++){
            if(deq.isEmpty()){
                deq.offerFirst(s.charAt(i));
            }else{
                if(deq.peekFirst() == s.charAt(i)){
                    deq.pollFirst();
                }else{
                    deq.offerFirst(s.charAt(i));
                }
            }
        }
        while(!deq.isEmpty()){
            sb.append(deq.pollLast());
        }
        return sb.toString();
    }
}

三、力扣150. 逆波兰表达式求值

class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> deq = new ArrayDeque<>();
        for(int i = 0; i < tokens.length; i ++){
            if("+".equals(tokens[i])){
                int right = deq.pollFirst();
                int left = deq.pollFirst();
                deq.offerFirst(left + right);
            }else if("-".equals(tokens[i])){
                int right = deq.pollFirst();
                int left = deq.pollFirst();
                deq.offerFirst(left - right);
            }else if("*".equals(tokens[i])){
                int right = deq.pollFirst();
                int left = deq.pollFirst();
                deq.offerFirst(left * right);
            }else if("/".equals(tokens[i])){
                int right = deq.pollFirst();
                int left = deq.pollFirst();
                deq.offerFirst(left / right);
            }else{
                deq.offerFirst(Integer.parseInt(tokens[i]));
            }
        }
        return deq.pollFirst();
    }
}

你可能感兴趣的:(java,算法,数据结构,leetcode)