网址
题目
给定一堆括号,找出能匹配的子串的最大长度。
解法1 栈
- 刚开始我自己的想法也是用栈,但push进去的是括号,后来发觉这样做无法定义连续,才想到栈应该存储的是索引,但怎么放索引脑子很混搞不清楚
- 看了leetcode的solution,它的做法是存入合法序列前一个位置的索引,方便后面计算长度。那什么样的位置可能是合法序列前一个位置的索引呢?一是右括号,前面没有能匹配的左括号;二是左括号,后面没有能匹配的右括号。当遇到右括号时,需要分类讨论,如果栈为空,需要push进当前索引以保证下次还能pop,否则就计算当前最大长度。
import java.util.Stack;
class Solution {
public int longestValidParentheses(String s) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(-1);
int res = 0;
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{
res = Math.max(res, i-stack.peek());
}
}
}
return res;
}
}
解法2 暴力破解优化
- 网上看到的很有意思的做法,时间复杂度O( n 2 n^2 n2)
public int longestValidParentheses(String s) {
int count = 0;
int max = 0;
for (int i = 0; i < s.length(); i++) {
count = 0;
for (int j = i; j < s.length(); j++) {
if (s.charAt(j) == '(') {
count++;
} else {
count--;
}
//count < 0 说明右括号多了,此时无论后边是什么,一定是非法字符串了,所以可以提前结束循环
if (count < 0) {
break;
}
//当前是合法序列,更新最长长度
if (count == 0) {
if (j - i + 1 > max) {
max = j - i + 1;
}
}
}
}
return max;
}
解法3 动态规划
- 初始化所有dp为0,如果当前位置为左括号则是非法序列,dp为0;如果当前位置为右括号则分两种情况讨论:
- 该括号前面为左括号
dp [ i ] = dp [ i - 2 ] + 2
- 该括号前面为右括号 dp [ i ] = dp [ i - 1 ] + dp [ i - dp [ i - 1] - 2 ] + 2
- 该括号前面为左括号
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;
}
}
解法4 O(1)空间
- 这个做法就很厉害了!
public class Solution {
public int longestValidParentheses(String s) {
int left = 0, right = 0, maxlength = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * right);
} else if (right >= left) {
left = right = 0;
}
}
left = right = 0;
for (int i = s.length() - 1; i >= 0; i--) {
if (s.charAt(i) == '(') {
left++;
} else {
right++;
}
if (left == right) {
maxlength = Math.max(maxlength, 2 * left);
} else if (left >= right) {
left = right = 0;
}
}
return maxlength;
}
}