乘风破浪:LeetCode真题_032_Longest Valid Parentheses
2024-10-14 10:15:50
乘风破浪:LeetCode真题_032_Longest Valid Parentheses
一、前言
这也是非常有意思的一个题目,我们之前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,这次最简单的方法当然也不例外。
二、Longest Valid Parentheses
2.1 问题
2.2 分析与解决
通过分析题意,这里我们有几种方法:
暴力算法:
public class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push('(');
} else if (!stack.empty() && stack.peek() == '(') {
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
public int longestValidParentheses(String s) {
int maxlen = 0;
for (int i = 0; i < s.length(); i++) {
for (int j = i + 2; j <= s.length(); j+=2) {
if (isValid(s.substring(i, j))) {
maxlen = Math.max(maxlen, j - i);
}
}
}
return maxlen;
}
}
但是对于比较长的字符串就会超时了,因为时间复杂度为O(n~3):
第二种方法:动态规划
我们使用dp[i]表示前面的i个字符的最大有效括号长度,因此dp[0]=0,dp[1]=0,于是就可以开始推出一个公式来计算了。
public class Solution {
public int longestValidParentheses(String s) {
int maxans = 0;
int dp[] = new int[s.length()];
for (int i = 1; i < s.length(); i++) {
if (s.charAt(i) == ')') {
if (s.charAt(i - 1) == '(') {
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
} else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {
dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
}
maxans = Math.max(maxans, dp[i]);
}
}
return maxans;
}
}
方法三:通过我们的方法,堆栈,很清晰很容易的解决了问题。
public class Solution { public int longestValidParentheses(String s) {
int maxans = 0;
Stack<Integer> stack = new Stack<>();
stack.push(-1);
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
stack.push(i);
} else {
stack.pop();
if (stack.empty()) {
stack.push(i);
} else {
maxans = Math.max(maxans, i - stack.peek());
}
}
}
return maxans;
}
}
当然还有其他的方法,在此不再赘述。
三、总结
在我们遇到括号的时候一定要想到使用堆栈来解决,当然动态规划是比较难的,我们也要理解和使用。
最新文章
- 无法访问org.springframework.core.NestedRuntimeException 找不到org.springframework.core.NestedRuntimeException的类文件
- Servlet生命周期+工作原理
- Linux下shell颜色配置
- java 14 - 8 DateFormat
- Java [leetcode 2] Add Two Numbers
- Java读取文件方法和给文件追加内容
- DOM手术台
- SVN Access to &#39;/svn/Test/!svn/me&#39; forbidden,不能更新解决办法
- MySql-时间格式转换之转换为时分秒格式的日期
- php 创建删除数据库
- iOS 中的单例设计模式
- SpringBoot时间戳与MySql数据库记录相差14小时排错
- 图解HTTP(1)之WEB及网络基础
- U3D一些使用
- TCP协议三次握手、四次挥手
- SQL Server 的 RowGuid/RowGuidCol 是什么意思?
- PHP-Redis操作
- javascript报错集锦
- 做网站,乱码?应该选用什么编码?GB2312 ? UTF-8 ?
- RxJava + Retrofit完成网络请求
热门文章
- org.hibernate.NonUniqueObjectException:a different object with the same identifier value was alread
- linux-openvpn
- 使用whiptail开发linux环境交互式对话框
- 如何从GitHub迁移到GitLab?
- 在MVC应用程序中,怎样删除上传的文件
- 定时器--Quartz.Net
- thinkphp ajax删除 隐藏与显示
- 记录怎样把安全证书导入到java中的cacerts证书库
- IDEA中的git更新项目
- Incircle and Circumcircle(二分+几何)浙大月赛zoj3806(详解版)图