Description
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example
Example 1:
Input: “(()”
Output: 2
Explanation: The longest valid parentheses substring is “()”
Example 2:
Input: “)()())”
Output: 4
Explanation: The longest valid parentheses substring is “()()”
Analyse
题目就是题意,要求你找出最长的有效括号对,并输出其长度。我们可以通过栈的形式去匹配括号,在匹配的同时,要是有不满足匹配的括号情况出现,将其位置留在栈中,那么两个位置之间长度即是我们有效匹配括号对的长度,然后在其之中找出最长的即可。
Code
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length(), longest = 0;
stack<int> st;
for (int i = 0; i < n; i++) {
if (s[i] == '(') st.push(i);
else {
if (!st.empty()) {
if (s[st.top()] == '(') st.pop();
else st.push(i);
}
else st.push(i);
}
}
if (st.empty()) longest = n;
else {
int a = n, b = 0;
while (!st.empty()) {
b = st.top(); st.pop();
longest = max(longest, a - b - 1);
a = b;
}
longest = max(longest, a);
}
return longest;
}
};