这也是很是有意思的一个题目,咱们以前已经遇到过两个这种括号的题目了,基本上都要用到堆栈来解决,此次最简单的方法固然也不例外。java
经过分析题意,这里咱们有几种方法:算法
暴力算法:spa
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):3d
第二种方法:动态规划blog
咱们使用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; } }
方法三:经过咱们的方法,堆栈,很清晰很容易的解决了问题。string
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; } }
固然还有其余的方法,在此再也不赘述。io
在咱们遇到括号的时候必定要想到使用堆栈来解决,固然动态规划是比较难的,咱们也要理解和使用。class