博客
关于我
LeetCode-32.最长有效括号
阅读量:801 次
发布时间:2023-01-31

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

给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。

示例 1:

输入: "(()"输出: 2解释: 最长有效括号子串为 "()"

示例 2:

输入: ")()())"输出: 4解释: 最长有效括号子串为 "()()"
1 /* 2     采用动态规划建立一个与给定字符串长度相等的数组dp,用于记录当前的有效括号长度 3     1.从下标为1的开始遍历,若当前下标为i的字符为'('时,则跳过(默认置为0) 4     2.若当前下标为i的字符为')’时,获取dp[]中前一个字符的数值,即dp[i-1],并获取指向的前dp[i-1]个字符下标(跳过有效括号字串,寻找前面未匹配的括号) 5     3.若有效括号字串的前一个字符为'(',即匹配成功,当前dp[i]获得前一个的数值加二(即dp[i]=dp[i-1]+2,2分别为()括号) 6     4.判断是否连续的有效括号:获得刚匹配成功的前一个dp数值,查看是否为0(即dp[i-2-dp[i-1]]),若不为0,则相当于连续字串,最后再加上dp[i-2-dp[i-1]]. 7 */ 8 class Solution { 9     public int longestValidParentheses(String s) {10         int len=s.length();11         int max=0;12         int []dp=new int[len];13         for(int i=1;i
=0){26 if(dp[lastindex]!=0)27 dp[i]+=dp[lastindex];28 }29 }30 if(dp[i]>max)31 max=dp[i];32 }33 return max;34 }35 }

 

 

转载于:https://www.cnblogs.com/lyh28/p/10512554.html

你可能感兴趣的文章
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 '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 'pandads'
查看>>
No module named cv2
查看>>