博客
关于我
leetcode做题记录0020
阅读量:349 次
发布时间:2019-03-04

本文共 961 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要判断给定的括号字符串是否正确匹配。我们可以使用栈来解决这个问题,因为栈非常适合处理嵌套结构。

思路

  • 初始化栈:使用一个栈来记录括号的位置。
  • 遍历字符串:逐个字符处理字符串中的每个字符。
    • 遇到左括号'(',将其推入栈。
    • 遇到右括号')',检查栈顶是否是左括号'(':
      • 如果栈为空,说明没有对应的左括号,返回false。
      • 如果栈顶不是左括号,说明括号不匹配,返回false。
  • 处理循环结束:遍历结束后,栈中如果还有元素,说明有多余的左括号,返回false。
  • 返回结果:如果所有括号都正确匹配且栈为空,返回true。
  • 代码

    import java.util.LinkedList;public class Solution {    public boolean isValid(String s) {        if (s.length() == 0) {            return true;        }        LinkedList
    stack = new LinkedList<>(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '(') { stack.add(c); } else if (c == ')') { if (stack.isEmpty() || stack.pop() != '(') { return false; } } } return stack.isEmpty(); }}

    解释

    • 初始化栈:使用LinkedList来模拟栈,因为它可以动态增长和缩短,非常适合这个问题。
    • 遍历字符串:逐个字符处理字符串,处理左括号和右括号,右括号则检查栈顶是否为左括号。
    • 处理循环结束:检查栈是否为空,栈不为空则说明有多余的左括号。
    • 返回结果:根据栈的状态返回是否正确匹配。

    转载地址:http://erhe.baihongyu.com/

    你可能感兴趣的文章
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>
    NPM酷库052:sax,按流解析XML
    查看>>
    npm错误 gyp错误 vs版本不对 msvs_version不兼容
    查看>>
    npm错误Error: Cannot find module ‘postcss-loader‘
    查看>>