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 “()()”
翻译
给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: "(()"
输出: 2
解释: 最长有效括号子串为 “()”
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 “()()”
分析
很久之前写的解法了,复杂度为O(n^2),由于数据量不大勉强过了。正确做法还是应该用栈或者动态规划。
c++实现
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0;
bool found = false;
for (int i = 0; i < s.length(); i++)
{
int length = 0;
int tmp = 0;
int start = i;
for (int j = i; j < s.length(); j++)
{
if (s[j] == '(')
tmp++;
else
tmp--;
if (tmp == 0)
{
length += j+1-start;
start = j+1;
if (res < length)
res = length;
}
if (tmp < 0)
{
length = 0;
start = j+1;
tmp = 0;
}
}
}
return res;
}
};