打卡第11天——20. 有效的括号 1047. 删除字符串中的所有相邻重复项 150. 逆波兰表达式求值

20. 有效的括号

1.题目描述

 力扣链接

2.适用场景

3.做题思路

charAt(i)是String类中的一个方法,用于返回字符串中索引为i位置的字符。

Deque<Character> 表示一个双端队列(Deque)类型,该队列中存储的元素类型是Character,即字符类型

在队列中放右括号,对比

4.代码实现

class Solution {
    public boolean isValid(String s) {
        Deque <Character> deque = new LinkedList <>();
        char ch;
        for(int i = 0; i<s.length(); i++){
            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.pop();}
        }
        return deque.isEmpty();
    }
}

5.总结 

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

1.题目描述

 力扣链接

2.适用场景

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

3.做题思路

 消消乐

4.代码实现

class Solution {
    public String removeDuplicates(String s) {
        ArrayDeque<Character> deque = new ArrayDeque<>();
        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;
    }
}

5.总结 

空字符串定义是“”,不是‘’ 

堆栈

150. 逆波兰表达式求值

1.题目描述

 力扣链接

2.适用场景

  • 时间复杂度: O(n)
  • 空间复杂度: O(n)

3.做题思路

 也是两个数的消消乐

4.代码实现

class Solution {
    public int evalRPN(String[] tokens) {
        Deque<Integer> stack = new LinkedList();
        for (String s : tokens) {
            if ("+".equals(s)) {
                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();
    }
}

5.总结 

 .valueOf(s)方法将字符串s转换为对应的整数形式

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值