给定一个只包含
'('
和')'
的字符串,找出最长的包含有效括号的子串的长度。示例 1:
输入: ")()())
" 输出: 4 解释: 最长有效括号子串为 "()()"
public int longestValidParentheses(String s)
{
// 先对字符串s进行判断
if (s == null || s.length()<=1)
return 0;
int n = s.length();
int leftBracket = 0; // 左括号数
int couple = 0; // 成对括号数
int[] tagArray = new int[n]; // 标记数组
Arrays.fill(tagArray, -2);
int[] leftBracketIdx = new int[n+1]; // 记录左括号的下标
int len = -1;
// 一次遍历做标记
for (int i=0; i<n; i++)
{
if (s.charAt(i) == '(')
{
tagArray[i] = -1; // 表示该位置为左括号
len++;
leftBracketIdx[len] = i; // 记录数组中末尾左括号的下标
leftBracket++;
}
else if (s.charAt(i) == ')' && leftBracket!=0)
{
tagArray[leftBracketIdx[len]] = 0; // 表示该左括号是有效的
len--;
tagArray[i] = 1; // 表示该位置有一个有效的括号
leftBracket--;
}
}
int a = 0;
// 第二次遍历
for (int j=0; j<n; j++)
{
// 发现一个未成对的左括号或右括号
if (tagArray[j] == -1 || tagArray[j] == -2)
{
couple = Math.max(a, couple);
a = 0;
}
// 发现一个成对括号
if (tagArray[j] == 1)
{
a++;
}
}
couple = Math.max(a, couple);
return couple*2;
}