[LeetCode] Longest Valid Parentheses

32. Longest Valid Parentheses

Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int longestValidParentheses(string s) {
vector<int> st {-1};
int res = 0;
for(int i = 0; i < s.length(); i++) {
if(s[i] == '(') {
st.push_back(i);
} else {
st.pop_back();
if(st.empty()) st.push_back(i);
else res = max(res, i - st.back());
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/longest-valid-parentheses/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.