- Longest Valid Parentheses
https://leetcode.com/problems/longest-valid-parentheses/description/
Difficulty:Hard
Total Accepted:151.5K
Total Submissions:629.9K
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 "()()"
解答过程:
一开始思路是计算可以与’(‘匹配的’)'数量来计算结果,但是这样算的答案不是不一定是字串的,例如"(()(()“用这个方法算出来的是4,将两个”()“都计算了,但这两个”()"并非连在一起的子字符串,正确答案应该为2
下面是一开始的错误代码:
class Solution {
public:
stack<int> STACK;//0代表左括号,1代表右括号
int longestValidParentheses(string s) {
int result=0;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') {
STACK.push(0);
}
else {
if (STACK.size() != 0) {
result += 2;
STACK.pop();
}
}
}
return result;
}
};
为了正确计算子字符串的长度,很明显需要将无法匹配的括号位置单独记录下来,上面的例子"(()(()“就需要将第0和第3号位置的”("单独记录位置以标记这两个端点。处理之后,两个子字符串范围分别为[1 ~ 2] 和 [4 ~ 5] ,取子字符串长度最长即为答案。
下面为最终代码:
class Solution {
public:
stack<int> STACK;//输入的数字代表对应的位置
int longestValidParentheses(string s) {
int result = 0;
for (int i = 0; i < s.size(); i++) {
if (STACK.size() != 0 && s[STACK.top()] == '('&&s[i]==')') {
STACK.pop();
}
else {
STACK.push(i);
}
}
if (STACK.size() == 0) {
result = s.size();
}
else {
int stackSize = STACK.size(), back = 0, front = 0;
result = s.size() - STACK.top() - 1;
for (int i = 0; i < stackSize - 1; i++) {
back = STACK.top();
STACK.pop();
front = STACK.top();
result = max(back - front - 1, result);
}
result = max(STACK.top(), result);
}
return result;
}
};