代码随想录算法训练营第11天|  20. 有效的括号 、1047. 删除字符串中的所有相邻重复项 、150. 逆波兰表达式求值

74 阅读1分钟

今日内容: 

●  20. 有效的括号

●  1047. 删除字符串中的所有相邻重复项

●  150. 逆波兰表达式求值

20. 有效的括号

判断三种情况,

image.png

class Solution {
    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            if(s.charAt(i) == '[') {
                stack.push(']');
            } else if(s.charAt(i) == '(') {
                stack.push(')');
            } else if(s.charAt(i) == '{') {
                stack.push('}');
            } else if(stack.isEmpty() || s.charAt(i) != stack.peek()) {
                return false;
            } else {
                stack.pop();
            }
        }
        if(!stack.isEmpty())return false;
        return true;
    }
}

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

用栈实现消消乐

class Solution {
    public String removeDuplicates(String s) {
        Deque<Character> deque = new LinkedList<>();
        char ch;
        for (int i = 0; i < s.length(); i++) {
            ch = s.charAt(i);
            if (deque.isEmpty() || deque.peek() != ch) {
                deque.push(ch);
            } else {
                deque.pop();
            }
        }
        String str = "";
        while(!deque.isEmpty()) {
            str = deque.pop() + str;
        }
        return str;
    }
}

150. 逆波兰表达式求值

class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new LinkedList();
        for (String s : tokens) {
            if ("+".equals(s)) {        // leetcode 内置jdk的问题,不能使用==判断字符串是否相等
                stack.push(stack.pop() + stack.pop());      // 注意 - 和/ 需要特殊处理
            } else if ("-".equals(s)) {
                stack.push(-stack.pop() + stack.pop());
            } else if ("*".equals(s)) {
                stack.push(stack.pop() * stack.pop());
            } else if ("/".equals(s)) {
                int temp1 = stack.pop();
                int temp2 = stack.pop();
                stack.push(temp2 / temp1);
            } else {
                stack.push(Integer.valueOf(s));
            }
        }
        return stack.pop();
    }
}