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();
    }
    }
    ```
相关推荐
DARLING Zero two♡9 小时前
【优选算法】D&C-Mergesort-Harmonies:分治-归并的算法之谐
java·数据结构·c++·算法·leetcode
Q741_14710 小时前
C++ 分治 归并排序 归并排序VS快速排序 力扣 912. 排序数组 题解 每日一题
c++·算法·leetcode·归并排序·分治
熬了夜的程序员20 小时前
【LeetCode】89. 格雷编码
算法·leetcode·链表·职场和发展·矩阵
dragoooon341 天前
[优选算法专题四.前缀和——NO.31~32 连续数组、矩阵区域和]
数据结构·算法·leetcode·1024程序员节
熬了夜的程序员1 天前
【LeetCode】87. 扰乱字符串
算法·leetcode·职场和发展·排序算法
·白小白1 天前
力扣(LeetCode) ——15.三数之和(C++)
c++·算法·leetcode
海琴烟Sunshine1 天前
leetcode 268. 丢失的数字 python
python·算法·leetcode
仰泳的熊猫1 天前
LeetCode:268. 丢失的数字
数据结构·c++·算法·leetcode
VT.馒头1 天前
【力扣】2725. 间隔取消
javascript·leetcode·1024程序员节
咪咪渝粮1 天前
108. 将有序数组转换为二叉搜索树
算法·leetcode