博客
关于我
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/

    你可能感兴趣的文章
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>