LeetCode

问题描述

给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。

有效字符串需满足:

左括号必须用相同类型的右括号闭合。

左括号必须以正确的顺序闭合。

每个右括号都有一个对应的相同类型的左括号。


原因分析:

困扰点一:

例如:关于接口类实例化的理解:

  • new LinkedList<Character>():在堆内存中创建一个LinkedList对象。这个对象是LinkedList类的一个实例。

  • Deque<Character> stack:声明一个引用变量stack,它的类型是Deque接口。这意味着这个变量可以指向任何实现了Deque接口的类的对象。

  • stack变量指向刚刚创建的LinkedList对象。因为LinkedList实现了Deque接口,所以这是允许的。
    new LinkedList的意义在哪里?

  • new LinkedList()的意义在于创建一个具体的、实现了Deque接口的LinkedList对象。虽然我们通过Deque接口的引用来操作这个对象,但实际在内存中的对象是LinkedList类型的。
  • 这样做的好处是:我们可以利用多态性。我们可以在不改变使用Deque接口的代码的情况下,更换具体的实现类。比如,我们可以将new LinkedList<>()改为new ArrayDeque<>(),而使用stack的代码不需要改变。

困扰点二:

java 复制代码
for (char c : s.toCharArray()) {
    // 循环体
}

/*
for (元素类型 临时变量 : 集合或数组) {
    // 使用临时变量
}

String s = "hello";
char[] chars = s.toCharArray(); 
// 结果:['h','e','l','l','o']

char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
    char c = chars[i];
    // 循环体
}*/

解决方案:

java 复制代码
class Solution {
    public boolean isValid(String s) {
        if(s.length() % 2 != 0)
        return false;
        Deque<Character> stack =new ArrayDeque<Character>();
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c =='(' ||c == '[' || c == '{'){
        stack .push(c);
    }else{
        if(stack.isEmpty())return false;
        char top = stack.pop();
        if (c == ')' && top != '(') return false;
                if (c == ']' && top != '[') return false;
                if (c == '}' && top != '{') return false;
            
    
    }
        }
         return stack.isEmpty();
    }
    }
    ```
相关推荐
琢磨先生David4 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
超级大福宝4 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
Charlie_lll4 天前
力扣解题-88. 合并两个有序数组
后端·算法·leetcode
菜鸡儿齐4 天前
leetcode-最小栈
java·算法·leetcode
Frostnova丶4 天前
LeetCode 1356. 根据数字二进制下1的数目排序
数据结构·算法·leetcode
im_AMBER4 天前
Leetcode 127 删除有序数组中的重复项 | 删除有序数组中的重复项 II
数据结构·学习·算法·leetcode
样例过了就是过了4 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
tyb3333335 天前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
踩坑记录5 天前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder1235 天前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode