题目连接
https://leetcode.com/problems/longest-valid-parentheses/
Longest Valid Parentheses
Description
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
记录括号出现的位置,找连续最长的一段。。
class Solution {
public:
int longestValidParentheses(string s) {
if (s.empty()) return 0;
int n = s.length();
stack<int> st;
vector<bool> vis(n + 10);
for (int i = 0; i < n; i++) {
char &c = s[i];
if (c == '(') {
st.push(i);
} else if (c == ')' && !st.empty()){
vis[i] = true;
vis[st.top()] = true; st.pop();
}
}
int ans = 0, ret = 0;
for (int i = 0; i < n; i++) {
if (vis[i]) ++ret;
else ret = 0;
ans = max(ans, ret);
}
return ans;
}
};