代码随想录第十一天

第五章 栈与队列****part02

20. 有效的括号

题目链接/文章讲解/视频讲解:https://programmercarl.com/0020.%E6%9C%89%E6%95%88%E7%9A%84%E6%8B%AC%E5%8F%B7.html

思路:

步骤:

  1. 创建一个空栈 stack

  2. 遍历字符串 s 中的每个字符:

    • 如果字符是左括号 '(''{''[',则将其入栈。

    • 如果字符是右括号 ‘)’,‘}’ 或 ‘]’:

      • 如果栈为空,或者栈顶元素与当前字符不匹配,则返回 false,说明字符串无效。
      • 如果栈不为空且栈顶元素与当前字符匹配,则将栈顶元素出栈。
  3. 遍历完字符串后,如果栈为空,则说明所有括号都匹配成功,返回 true,否则返回 false

完整代码

import java.util.Stack;

class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String s1 = "()";
        System.out.println(solution.isValid(s1)); // 输出 true
        
        String s2 = "()[]{}";
        System.out.println(solution.isValid(s2)); // 输出 true
        
        String s3 = "(]";
        System.out.println(solution.isValid(s3)); // 输出 false
        
        String s4 = "([)]";
        System.out.println(solution.isValid(s4)); // 输出 false
        
        String s5 = "{[]}";
        System.out.println(solution.isValid(s5)); // 输出 true
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c : s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else if (c == ')' || c == '}' || c == ']') {
                if (stack.isEmpty() || !isMatching(stack.peek(), c)) {
                    return false;
                }
                stack.pop();
            }
        }
        return stack.isEmpty();
    }
    
    private boolean isMatching(char left, char right) {
        return (left == '(' && right == ')') ||
               (left == '{' && right == '}') ||
               (left == '[' && right == ']');
    }
}

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

题目链接/文章讲解/视频讲解:https://programmercarl.com/1047.%E5%88%A0%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E4%B8%AD%E7%9A%84%E6%89%80%E6%9C%89%E7%9B%B8%E9%82%BB%E9%87%8D%E5%A4%8D%E9%A1%B9.html

思路:

使用栈来进行重复项删除操作。我们遍历字符串 S 中的每个字符,如果当前字符和栈顶元素相同,则将栈顶元素出栈;否则将当前字符入栈。

最后,我们将栈中的元素按照出栈的顺序组成字符串,并反转字符串得到最终结果。

步骤:

完整代码

import java.util.Stack;

public class Solution {
    public String removeDuplicates(String S) {
        Stack<Character> stack = new Stack<>();

        for (char c : S.toCharArray()) {
            if (!stack.isEmpty() && stack.peek() == c) {
                stack.pop();
            } else {
                stack.push(c);
            }
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }

        return sb.reverse().toString();
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String S = "abbaca";
        String result = solution.removeDuplicates(S);
        System.out.println(result); // 输出 "ca"
    }
}

150. 逆波兰表达式求值

题目链接/文章讲解/视频讲解:https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html

思路:

这个算法的思路是使用栈来实现逆波兰表达式的计算。我们遍历字符串数组 tokens 中的每个元素,如果当前元素是操作符,则从栈中取出两个数进行计算,并将结果压入栈中;否则,将元素转换为整数并压入栈中。

最终,栈中只剩下一个元素,即为表达式的计算结果。

步骤:

完整代码

import java.util.Stack;

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<>();
        
        for (String token : tokens) {
            if (token.equals("+")) {
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1 + num2);
            } else if (token.equals("-")) {
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1 - num2);
            } else if (token.equals("*")) {
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1 * num2);
            } else if (token.equals("/")) {
                int num2 = stack.pop();
                int num1 = stack.pop();
                stack.push(num1 / num2);
            } else {
                stack.push(Integer.parseInt(token));
            }
        }
        
        return stack.pop();
    }
}

public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        String[] tokens = {"2", "1", "+", "3", "*"};
        int result = solution.evalRPN(tokens);
        System.out.println(result); // 输出 9
    }
}

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值