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

发布于:2024-06-01 ⋅ 阅读:(134) ⋅ 点赞:(0)

# 20. 有效的括号

class Solution {
    public boolean isValid(String s) {
            char[] s_Array = s.toCharArray();
            Stack<Character> stack = new Stack<Character>();
            for(char c:s_Array){
                if(c == '('){
                    stack.push(')');
                }else if(c == '['){
                    stack.push(']');
                }else if(c == '{'){
                    stack.push('}');
                }else{
                    if(stack.isEmpty() || stack.pop() != c){
                        return false;
                    }
                }
            }
            if(!stack.isEmpty()){
                return false;
            }
            return true;
    }
}

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

class Solution {
    public String removeDuplicates(String s) {
       Stack<Character> stack = new Stack<Character>();
       for(char c:s.toCharArray()){
            if(!stack.isEmpty() && stack.peek() == c){
                stack.pop();
            }else{
                stack.push(c);
            }
        }
        StringBuilder str = new StringBuilder();
        while(!stack.isEmpty()){
            str.insert(0,stack.pop());
//这里将弹出的数直接加到字符串的头,就不用再反转字符串return了
        }
        return str.toString();
    }
}

150.逆波特兰表达式求值

这道题几个注意点都在注释中标注

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        for(String s:tokens){
            if(isNumber(s)){
                stack.push(Integer.parseInt(s));
            }else{
                if(s.equals("+")){
                    //务必要记住引用数据类型判断相等用equals,因为==比较的是对象的引用,equals是比较的内容
                    stack.push(stack.pop()+stack.pop());
                }else if(s.equals("/")){
                    //注意这里的顺序,先弹出的作为除数
                    int temp1 = stack.pop();
                    int temp2 = stack.pop();
                    stack.push(temp2/temp1);
                }else if(s.equals("*")){
                    stack.push(stack.pop() * stack.pop());
                }else if(s.equals("-")){
                    //注意这里的顺序,先弹出的作为减数
                    int temp1 = stack.pop();
                    int temp2 = stack.pop();
                    stack.push(temp2 - temp1);
                }
            }
        }
        return stack.pop();
    }
    //判断字符串是不是数字
    public static boolean isNumber(String s){
        //这里注意判断的应该是最后一个字符,是数字的字符串最后一个字符一定是数字
        return Character.isDigit(s.toCharArray()[s.length()-1]);
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到