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.
思路:
标记所有成对括号,于是不成对括号成为间隔符,问题变为寻找串内间隔符之间最长的子串。
题解:
做法可以简化,这个代码主要用来描述思路。
int longestValidParentheses(const std::string& s) {
const int UNPAIRED = -1;
const int LEN = s.size();
std::vector<int> pairing(LEN, UNPAIRED);
std::stack<int> lParentheses;
for(int i = 0; i < LEN; ++i) {
if (s[i] == '(') {
lParentheses.push(i);
} else if (!lParentheses.empty()) {
int last = lParentheses.top();
pairing[i] = last;
pairing[last] = i;
lParentheses.pop();
}
}
int maxLength = 0, currentLength = 0;
for(auto i: pairing) {
if (i != UNPAIRED) {
++currentLength;
} else {
maxLength = std::max(maxLength, currentLength);
currentLength = 0;
}
}
return std::max(maxLength, currentLength);
}