当前位置:网站首页>【力扣刷题】32. 最长有效括号
【力扣刷题】32. 最长有效括号
2022-07-06 12:56:00 【李小恩恩子】
目录
方法一:
题目:
给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。

方法一:
解题思路:
利用栈,学过利用栈来判断一个只包含'('和')'的字符串是否是括号匹配的,那个题目解题就是,遍历整个字符串,是左括号就入栈,是右括号则①判断栈是否有左括号且弹出一个左括号,②如果栈为空则为false,如果所有字符都遍历完了,栈中还有元素则为false,否则为true。
利用这个思路,增加一个标记数组arr,初始化所有元素为1,栈中存的是数组下标(字符索引)。遍历整个字符串,如果是左括号则把索引下标(i)加入栈,如果是右括号则判断栈中元素是否为空且不为空则弹出,并把标记数组对应的元素arr[stack.pop()]以及当前下标对应的标记数组元素arr[i]置为0。
最后判断标记数组arr的最长连续0就可以了。
代码:
class Solution {
public int longestValidParentheses(String s) {
//要找最长的有效括号
//栈
//利用栈来标记左右括号是否有效,栈的内容存下标i
Stack<Integer> stack = new Stack<>();
int[] valid = new int[s.length()];
for(int i = 0; i < s.length(); i++){
valid[i] = 1;
}
for(int i = 0; i < s.length();i++){
if(s.charAt(i) == '(') stack.push(i);
else{
if(!stack.empty()){
valid[i] = 0;
valid[stack.pop()] = 0;
}
}
}
int res = 0,count = 0;
for(int i = 0; i < s.length();i++){
if(valid[i] == 1) {
count = 0;
}else{
count++;
}
res = Math.max(res,count);
}
return res;
}
}方法二:
解题思路:
动态规划,利用dp[i]表示以下标i字符结尾的最长有效括号的长度。将dp数组全部初始化为0。有效的子串一定以')'结尾,以'('结尾的子串对应的dp值必定为0。所以只需要求解以')'在dp数组中对应位置的值。所以从前往后遍历字符串,求解dp值。
①s.charAt(i)=')'且s.charAt(i-1)='(',字符串为"...()"则dp[i] = dp[i-2]+2。
②如果s.charAt(i) = ')'且s.charAt(i-1) = ')',比如字符串"...))"->"()(())",
如果s.charAt(i - dp[i - 1] - 1)='(',那么有效括号长度新增长度2,i位置对最长有效括号长度为 i-1位置的最长括号长度加上当前位置新增的2,不过得注意,i − dp[i − 1] − 1 和 i 组成了有效括号对,这将是一段独立的有效括号序列,如果之前的子序列是形如 (...)(...) 这种序列,那么当前位置的最长有效括号长度还需要加上这一段。例如:()(()),左边红色的和右边绿色的为两个独立的有效括号序列。所以状态转移方程为:dp[i] = dp[i - 1] + 2 + dp[i - dp[i - 1] -2 ]。
图示:

还要注意边界值,因为要用到 dp[ i - 2 ],还有dp[ i - dp[ i - 1 ] - 2 ],要判断。
代码:
class Solution {
public int longestValidParentheses(String s) {
//动态规划
//dp[i]表示以下标i字符结尾的最长有效括号的长度
int res = 0;
int[] dp = new int[s.length()];
for(int i = 1;i < s.length();i++){
if(s.charAt(i) == ')'){
if(s.charAt(i-1) == '('){
if(i >= 2) dp[i] = dp[i - 2] + 2;
else dp[i] = 2;
}else if(i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '('){
if(i - dp[i - 1] >= 2) dp[i] = dp[i - 1] + dp[i - dp[i - 1] - 2] + 2;
else dp[i] = dp[i - 1] + 2;
}
}
res = Math.max(res,dp[i]);
}
return res;
}
}方法二看了看解析,不太会写动态规划,下次找个机会专门练一练动态规划的题目。
边栏推荐
- PG基础篇--逻辑结构管理(事务)
- Opencv learning example code 3.2.3 image binarization
- for循环中break与continue的区别——break-完全结束循环 & continue-终止本次循环
- 全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀
- Simple continuous viewing PTA
- Is it profitable to host an Olympic Games?
- Manifest of SAP ui5 framework json
- Pat 1085 perfect sequence (25 points) perfect sequence
- Le langage r visualise les relations entre plus de deux variables de classification (catégories), crée des plots Mosaiques en utilisant la fonction Mosaic dans le paquet VCD, et visualise les relation
- Reflection operation exercise
猜你喜欢

for循环中break与continue的区别——break-完全结束循环 & continue-终止本次循环

HMS core machine learning service creates a new "sound" state of simultaneous interpreting translation, and AI makes international exchanges smoother
![[MySQL] trigger](/img/b5/6df17eb254bbdb0aba422d08f13046.png)
[MySQL] trigger

039. (2.8) thoughts in the ward
![[MySQL] basic use of cursor](/img/cc/39b1e17b48d0de641d3cbffbf2335a.png)
[MySQL] basic use of cursor

全网最全的新型数据库、多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、维格表 Vika、飞书多维表格、黑帕云、织信 Informat、语雀

What is the problem with the SQL group by statement

硬件开发笔记(十): 硬件开发基本流程,制作一个USB转RS232的模块(九):创建CH340G/MAX232封装库sop-16并关联原理图元器件

Data Lake (VIII): Iceberg data storage format

Swagger UI教程 API 文档神器
随机推荐
Interviewer: what is the internal implementation of ordered collection in redis?
【论文解读】用于白内障分级/分类的机器学习技术
Math symbols in lists
1_ Introduction to go language
华为设备命令
Tips for web development: skillfully use ThreadLocal to avoid layer by layer value transmission
【mysql】游标的基本使用
Hardware development notes (10): basic process of hardware development, making a USB to RS232 module (9): create ch340g/max232 package library sop-16 and associate principle primitive devices
分糖果
Reviewer dis's whole research direction is not just reviewing my manuscript. What should I do?
[200 opencv routines] 220 Mosaic the image
What are RDB and AOF
The difference between break and continue in the for loop -- break completely end the loop & continue terminate this loop
None of the strongest kings in the monitoring industry!
@Detailed differences among getmapping, @postmapping and @requestmapping, with actual combat code (all)
El table table - sortable sorting & disordered sorting when decimal and% appear
JS get array subscript through array content
Pinduoduo lost the lawsuit, and the case of bargain price difference of 0.9% was sentenced; Wechat internal test, the same mobile phone number can register two account functions; 2022 fields Awards an
C # use Oracle stored procedure to obtain result set instance
【滑动窗口】第九届蓝桥杯省赛B组:日志统计