乘风破浪: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;
}
}

     当然还有其他的方法,在此不再赘述。

三、总结

在我们遇到括号的时候一定要想到使用堆栈来解决,当然动态规划是比较难的,我们也要理解和使用。

最新文章

  1. 无法访问org.springframework.core.NestedRuntimeException 找不到org.springframework.core.NestedRuntimeException的类文件
  2. Servlet生命周期+工作原理
  3. Linux下shell颜色配置
  4. java 14 - 8 DateFormat
  5. Java [leetcode 2] Add Two Numbers
  6. Java读取文件方法和给文件追加内容
  7. DOM手术台
  8. SVN Access to &#39;/svn/Test/!svn/me&#39; forbidden,不能更新解决办法
  9. MySql-时间格式转换之转换为时分秒格式的日期
  10. php 创建删除数据库
  11. iOS 中的单例设计模式
  12. SpringBoot时间戳与MySql数据库记录相差14小时排错
  13. 图解HTTP(1)之WEB及网络基础
  14. U3D一些使用
  15. TCP协议三次握手、四次挥手
  16. SQL Server 的 RowGuid/RowGuidCol 是什么意思?
  17. PHP-Redis操作
  18. javascript报错集锦
  19. 做网站,乱码?应该选用什么编码?GB2312 ? UTF-8 ?
  20. RxJava + Retrofit完成网络请求

热门文章

  1. org.hibernate.NonUniqueObjectException:a different object with the same identifier value was alread
  2. linux-openvpn
  3. 使用whiptail开发linux环境交互式对话框
  4. 如何从GitHub迁移到GitLab?
  5. 在MVC应用程序中,怎样删除上传的文件
  6. 定时器--Quartz.Net
  7. thinkphp ajax删除 隐藏与显示
  8. 记录怎样把安全证书导入到java中的cacerts证书库
  9. IDEA中的git更新项目
  10. Incircle and Circumcircle(二分+几何)浙大月赛zoj3806(详解版)图