leetcode - 20.有效的括号(LinkedHashMap)

news2024/11/16 21:26:02

leetcode题目有效的括号,分类是easy,但是博主前前后后提交了几十次才通过,现在记录一下使用Java语言的写法。
在这里插入图片描述

题目链接: 20.有效的括号

题目描述:

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

有效字符串需满足:
1.左括号必须用相同类型的右括号闭合。
2.左括号必须以正确的顺序闭合。
3.每个右括号都有一个对应的相同类型的左括号。

题目示例:

示例 1:
输入:s = "()"
输出:true

示例 2:
输入:s = "()[]{}"
输出:true

示例 3:
输入:s = "(]"
输出:false

题目提示:

1. <= s.length <= 104
2. 仅由括号 '()[]{}' 组成

题目解读:

每个左括号都要有成对的右括号,成对的含义是
(1)属于"()"、"[]"、"{}"中的任意一对
(2)中间不存在其他字符,比如"()"
(3)中间存在其他成对的字符,比如"({[]})"

示例图:
在这里插入图片描述

一、 递归

基于以上的理解,博主最初选择使用递归消除字符的做法。只要左右相邻的字符成对就将其消除,递归至LinkedHashMap的长度为0或不再出现可消除的字符。

思路:
(1)使用LinkedHashMap保存入参用例中的所有字符。
(2)遍历LinkedHashMap,在存在相邻两个元素符合成对匹配条件时,将这两个元素记录下来,在一次遍历结束后从LinkedHashMap中移除。
(3)当LinkedHashMap长度为0,或者在一次遍历中没有产生新的待删除的元素,则跳出循环。
(4)当最终LinkedHashMap长度为0时,说明全部匹配成功。
class Solution {
    public boolean isValid(String s) {

        boolean res = false;
        char[] charArray = s.toCharArray();
        if (charArray.length % 2==1) {
            return res;
        }
        HashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
        for (int i =0; i < charArray.length; i++) {
            linkedHashMap.put(i, String.valueOf(charArray[i]));
        }

        List<String> leftList = Arrays.asList("(", "[", "{");
        List<String> rightList = Arrays.asList(")", "]", "}");

        // 当map中全部消除完,或上一轮没有可消除的值时跳出循环
        int lastIndex = 0;
        List<Integer> removeKeys = new ArrayList<>();
        while (!linkedHashMap.isEmpty()) {
            removeKeys = new ArrayList<>();
            for (Integer key : linkedHashMap.keySet()) {

                int pos = new ArrayList<Integer>(linkedHashMap.keySet()).indexOf(key);

                // 从第二个开始跟前面的比较,前面取最新的linkedMap的第一个,不是key=0
                if (pos > 0) {
                    if (leftList.contains(linkedHashMap.get(lastIndex))
                            && rightList.contains(linkedHashMap.get(key))
                            && (leftList.indexOf(linkedHashMap.get(lastIndex)) == rightList.indexOf(linkedHashMap.get(key)))) {
                        // 删除对应位置
                        removeKeys.add(lastIndex);
                        removeKeys.add(key);
                        linkedHashMap.put(lastIndex, "0");
                        linkedHashMap.put(key, "0");
                    }
                }
                // 保存上一个key的值
                lastIndex = key;
            }

            if (!removeKeys.isEmpty()) {
                removeKeys.forEach(linkedHashMap::remove);
            } else {
                break;
            }
        }


        if (linkedHashMap.isEmpty()) {
            res = true;
        }


        return res;
    }

}

该做法可以计算正确,但在遇到以下测试用例时,惨遭Time Limit Exceeded 👇。

String s = "[([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([([()])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])])]";

该测试用例长度为7000,以递归消除元素的方法需要递归遍历几千次,速度非常的慢。那么,提高速度最好的办法就是减少遍历次数。

二、栈

在评论区看了一圈,发现大佬们的基本都是用栈来解决。
但是博主平时基本不使用栈这种数据结构,对栈的了解仅停留在以下层面。

栈(Stack)是一种常见的数据结构,具有后进先出(LIFO,Last In First Out)的特性,即最后入栈的元素最先出栈。

所以依然选择使用熟悉的LinkedHashMap去实现LIFO这一行为。在加入LinkedHashMap前先判断是否与末尾的元素匹配,再决定后续的操作。仅需要遍历一次就可以完成所有的匹配判断。

思路:
(1)遍历入参的字符数组。
(2)如果linkedMap长度为空,当前字符直接加入,作为第一个字符。
(3)如果linkedMap长度不为空,取末尾元素与当前元素进行匹配。匹配成功,将末尾元素消除(弹出);匹配失败,将当前元素加入linkedMap(压入)
(4)字符数组遍历结束后,如果linkedMap为空,说明全部匹配。
class Solution {
    public boolean isValid(String s) {

        boolean res = false;
        char[] charArray = s.toCharArray();
        if (charArray.length % 2==1) {
            return res;
        }

        List<String> leftList = Arrays.asList("(", "[", "{");
        List<String> rightList = Arrays.asList(")", "]", "}");

        // 栈:一个一个往堆栈里填入,如果跟前一个匹配就双双丢出
        HashMap<Integer, String> linkedHashMap = new LinkedHashMap<>();
        for (int i =0; i < charArray.length; i++) {
            String s1 = String.valueOf(charArray[i]);
            // 当前linkedMap中的排列的第一位
            if (i== 0 || linkedHashMap.isEmpty()) {
                if (rightList.contains(s1)) {
                    return false;
                }
                linkedHashMap.put(i, String.valueOf(charArray[i]));
            } else {

                int lastPos = new ArrayList<Integer>(linkedHashMap.keySet()).get(linkedHashMap.size()-1);
                // 判断跟linkedMap中最新一位元素是否匹配
                String lastS1 = linkedHashMap.get(lastPos);
                if (leftList.contains(lastS1)
                        && rightList.contains(s1)
                        && (leftList.indexOf(lastS1) == rightList.indexOf(s1))) {
                    // 匹配成功,不加入linkedMap,并且将前一个元素从map中移除(弹出)
                    linkedHashMap.remove(lastPos);

                } else {
                    // 不匹配,将该元素加入linkedMap中(压入)
                    linkedHashMap.put(i, String.valueOf(charArray[i]));
                }
            }
        }
        // 全部消除完毕才是通过
        if (linkedHashMap.isEmpty()) {
            res = true;
        }
        return res;
    }
}

不过在使用LinkedHashMap时也碰到了一些问题,因为元素可以随意移除,所以key的排序不是连续的12345等。需要将key转为ArrayList,再通过ArrayList.get()方法获取最新一位元素key。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1713823.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

SAP 生产订单报工函数BAPI_PRODORDCONF_CREATE_TT不返回报错信息

最近财务一直反馈MES报工的数据都没有成本,然后去查看原因发现是财务当月的KP26的价格没有进行维护,导致没有收集到工单的报工成本。 但是在前台操作CO11 报工的时候,系统会给出报错的信息 但是我们在调用函数BAPI_PRODORDCONF_CREATE_TT的时候,系统并没有返回报错的信息…

Windows电脑高颜值桌面便利贴,便签怎么设置

在这个看颜值的时代&#xff0c;我们不仅在衣着打扮上追求时尚与美观&#xff0c;就连电脑桌面也不愿放过。一张唯美的壁纸&#xff0c;几款别致的小工具&#xff0c;总能让我们的工作空间焕发出不一样的光彩。如果你也热衷于打造高颜值的电脑桌面&#xff0c;那么&#xff0c;…

下一代 CI/CD:利用 Tekton 和 ArgoCD 实现云原生自动化

一、回顾目标 背景&#xff1a; ​ 部门业务上云&#xff0c;之前服务采用传统的部署方式&#xff0c;这种方式简单&#xff0c;但是不能为应用程序定义资源使用边界&#xff0c;很难合理地分配计算资源&#xff0c;而且程序之间容易产生影响。随着互联网时代的到来&#xff…

Leetcode - 131双周赛

一&#xff0c;3158. 求出出现两次数字的 XOR 值 本题是一道纯模拟题&#xff0c;直接暴力。 代码如下&#xff1a; class Solution {public int duplicateNumbersXOR(int[] nums) {int ans 0;long t 0;for(int x : nums){if(((t>>x)&1) 1){ans ^ x;}else{t | (…

图片去水印工具(低调用哦)

一、简介 1、它是一款专业的图像编辑工具&#xff0c;旨在帮助用户轻松去除照片中不需要的元素或修复照片中的缺陷。无论是修复旧照片、消除拍摄时的不良构图&#xff0c;还是删除照片中的杂乱元素&#xff0c;都能帮助用户快速实现这些目标。其功能强大且操作简单&#xff0c…

代码随想录算法训练营第36期DAY43

DAY43 343整数拆分 注意&#xff1a;当几个数的数值相近&#xff0c;乘积才会尽可能地大&#xff08;好想&#xff1a;数一大一小&#xff0c;最大当然是自己乘以自己&#xff09; 代码随想录官方题解&#xff1a; class Solution {public: int integerBreak(int n) { …

在outlook的邮件中插入HTML;HTML模板获取

本文介绍如何在outlook发送邮件时&#xff0c;在邮件中插入HTML&#xff0c;此HTML可以从获取模板自行进行修改。 文章目录 一、下载HTML模板&#xff08;或自己制作好HTML文件&#xff09;二、outlook新增宏三、新建邮件&#xff0c;插入HTML 一、下载HTML模板&#xff08;或自…

某烟草企业数字化转型物流信息化咨询项目规划方案(117页PPT)

方案介绍&#xff1a; 烟草企业数字化转型物流信息化咨询项目规划方案将为企业带来多方面的价值&#xff0c;包括提升物流运营效率、降低物流成本、优化供应链管理、增强企业竞争力和促进可持续发展等。这些价值的实现将有助于企业在激烈的市场竞争中保持领先地位并实现可持续…

5292A 物联网信号分析仪

5292A 物联网信号分析仪 —— 10MHz&#xff5e;6GHz —— 简述 5292A物联网信号分析仪是一款通用的矢量信号分析仪&#xff0c;频率范围覆盖 10MHz&#xff5e;6GHz&#xff0c;具有良好的频率、功率测量精度和稳定度&#xff1b;支持模拟与数字调制信号、全制式的通信标准…

【408真题】2009-23

“接”是针对题目进行必要的分析&#xff0c;比较简略&#xff1b; “化”是对题目中所涉及到的知识点进行详细解释&#xff1b; “发”是对此题型的解题套路总结&#xff0c;并结合历年真题或者典型例题进行运用。 涉及到的知识全部来源于王道各科教材&#xff08;2025版&…

OpenCV:入门(四)

形态学操作 形态学&#xff0c;即数学形态学&#xff08;Mathematical Morphology&#xff09;&#xff0c;是图像处理过程中一个非常重要的研 究方向。形态学主要从图像内提取分量信息&#xff0c;该分量信息通常对于表达和描绘图像的形状具有 重要意义&#xff0c;通常是图像…

花钱学谢宁DOE培训,投入产出比到底如何?

在当今这个快速发展的时代&#xff0c;无论是职场人士还是创业者&#xff0c;都渴望通过不断学习来提升自我能力&#xff0c;以便在竞争激烈的市场中脱颖而出。其中&#xff0c;谢宁DOE培训因其独特的理念和方法&#xff0c;吸引了众多求学者的目光。然而&#xff0c;面对不菲的…

从零开始利用MATLAB进行FPGA设计(六)用ADC采集信号教程1

黑金的教程做的实在太拉闸了&#xff0c;于是自己摸索信号采集模块的使用方法。 ADC模块&#xff1a;AN9238 FPGA开发板&#xff1a;AX7020&#xff1b;Xilinx 公司的 Zynq7000 系列的芯片XC7Z020-2CLG400I&#xff0c;400引脚 FBGA 封装。 往期回顾&#xff1a; 从零开始利…

Vue项目运行页面禁止缩放【移动端和PC端都禁止缩放】解决方案

Vue项目运行页面禁止缩放【移动端和PC端都禁止缩放】解决方案&#xff0c;有的人手很J,总喜欢放大缩小&#xff0c;从而会导致页面错乱&#xff0c;以下是解决方案&#xff0c;简单有效 效果图PC&#xff1a;滚轮缩放和其他缩放都会禁止 移动端效果图&#xff1a;各种手机平板…

Python数据处理,使用 tkinter 模块点击获取文件目录

Python数据处理&#xff0c;使用 tkinter 模块点击获取文件目录 正文 正文 当我们进行数据处理读取文件内数据的时候&#xff0c;通常&#xff0c;我们需要设定好一个存放当前文件所在目录的变量。比如如下目录&#xff1a; file_path rC:\Users\xxx\Desktop\DataSet\Data.c…

20240528解决飞凌的OK3588-C的核心板的TYPE-C1接口识别问题

20240528解决飞凌的OK3588-C的核心板的TYPE-C1接口识别问题 2024/5/28 16:46 缘起&#xff1a; 现阶段碰到的USB相关的问题&#xff1a;&#xff08;LINUX R4版本&#xff09; 1、USB3.0插USB摄像头 lsusb找不到设备 2、刷机口只接了3根线&#xff0c;GND/D/D-&#xff0c;可以…

vue3 + ts 实现IP地址及Mac地址输入框功能

1、组件完成代码 <template><div class"ip-input"><div v-for"(item, index) in ipArr" :key"index" class"ip-input__item-wrap"><input ref"ipInput" v-model"ipArr[index]" type"t…

Python装饰器的应用

Python 中的装饰器是一种语法糖&#xff0c;可以在运行时&#xff0c;动态的给函数或类添加功能。装饰器本质上是一个函数&#xff0c;使用 函数名就是可实现绑定给函数的第二个功能 。它的作用就是在不修改被装饰对象源代码和调用方式的前提下为被装饰对象添加额外的功能。 …

清华大学提出IFT对齐算法,打破SFT与RLHF局限性

监督微调&#xff08;Supervised Fine-Tuning, SFT&#xff09;和基于人类反馈的强化学习&#xff08;Reinforcement Learning from Human Feedback, RLHF&#xff09;是预训练后提升语言模型能力的两大基础流程&#xff0c;其目标是使模型更贴近人类的偏好和需求。 考虑到监督…

奥利奥罚单背后的启示:企业合规与反垄断的边界

在全球化的经济环境中&#xff0c;企业面临着激烈的市场竞争。为了在竞争中脱颖而出&#xff0c;一些企业可能会采取不正当的竞争手段&#xff0c;如垄断、价格歧视等。然而&#xff0c;这些行为往往会触犯反垄断法规&#xff0c;给企业带来严重的法律风险。最近&#xff0c;奥…