问题描述
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
题目要求: 输入一个字符串,输出里面包含的最长的合法括号串的长度
解题思路
DP大法好!动态规划一下万事皆可。
创建数组,对应元素储存当前位置结尾的最长合法括号串。
考虑一下集中情况:
- 当前字符是
'('
:皆大欢喜,直接赋值为0,因为没有合法括号串是以’('结尾 - 当前字符是
')'
:两种可能性, 一个是(()()())
这种,最后一个字符的判断需要用到很多位之前的内容,这时候就需要找到对应位置的字符看是否是’(’,是的话就res[i] = res[i-1] + 2 + (再前面的长度) (例如()(()()())
这种。);另一种可能性是(())()
这种,以前面一个结尾的串不合法,所以要判断前面一个是不是'('
来跟当前字符')'
组成一队。
代码实现
public int longestValidParentheses(String s) {
if(s.length() <= 1)
return 0;
int[] res = new int[s.length()];
res[0] = 0;
res[1] = (s.charAt(0) == '(' && s.charAt(1) == ')')?2:0;
int result = res[1];
for(int i = 2; i < s.length(); i++) {
if(s.charAt(i) == '(')
res[i] = 0;
else {
int tmp1 = 0, tmp2 = 0;
if(res[i-1] != 0) {
if(i - res[i-1] - 1 >= 0 && s.charAt(i - res[i-1] - 1) == '(') {
tmp1 = res[i-1] + 2;
if(i - res[i-1] - 2 >= 0) //对应()(())这种情况,容易忽视最前面的()
tmp1 += res[i - res[i-1] - 2];
}
else
tmp1 = 0;
} else {
if(s.charAt(i-1) == '(') {
tmp2 = res[i-2] + 2;
} else
tmp2 = 0;
}
res[i] = Math.max(tmp1, tmp2);
}
result = Math.max(result, res[i]);
}
return result;
}
复杂度分析:
时间复杂度:O(n)
空间复杂度:O(n)