方法一:动态规划
思路:如果i对应的),则如果i-1一个为( ,则dp[i]=dp[i-2]+2;如果i-1为)查看i-1是否被匹配过。
public class Solution
{
//动态规划
public int LongestValidParentheses(string s)
{
int[] dp = new int[s.Length];
int answer = 0;
for (int i = 1; i < s.Length; i++)
{
if (s[i] == ')')
{
if (s[i - 1] == '(')
{
//如果匹配的话,结果=dp[i-2]+2
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
}
else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(')
{
dp[i] = dp[i - 1] + (i - dp[i - 1] >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
}
answer = Math.Max(answer, dp[i]);
}
}
return answer;
}
}
方法二:栈
思路:栈中存储位置索引。匹配的时候用索引减去栈中最后的索引。
public class Solution2
{
//栈方法
public int LongestValidParentheses(string s)
{
int answer = 0;
Stack<int> stack = new Stack<int>();
stack.Push(-1);
for (int i = 0; i < s.Length; i++)
{
if (s[i] == '(')
{
stack.Push(i);
}
else
{
stack.Pop();
if (stack.Count == 0)
{
stack.Push(i);
}
else
{
answer = Math.Max(answer, i - stack.Peek());
}
}
}
return answer;
}
}