您的位置:首页 > 其它

LeetCode题解:Longest Valid Parentheses

2017-01-17 13:17 381 查看
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode