LeetCode题解:Longest Valid Parentheses
2017-01-17 13:17
381 查看
Given a string containing just the characters
find the length of the longest valid (well-formed) parentheses substring.
For
which has length = 2.
Another example 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);
}
'('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题解:Longest Valid Parentheses
- [LeetCode]题解(python):032-Longest Valid Parentheses
- leetcode题解-13. Roman to Integer && 14. Longest Common Prefix && 20. Valid Parentheses
- LeetCode-32.Longest Valid Parentheses最长有效括号子串
- leetcode题解-32. Longest Valid Parentheses
- [leetcode] Longest Valid Parentheses
- LeetCode--Longest Valid Parentheses
- Leetcode 栈 Longest Valid Parentheses
- Leetcode题解14 20. Valid Parentheses
- leetcode(32) Longest Valid Parentheses
- leetcode题解:Valid Parentheses(栈的应用-括号匹配)
- 【leetcode】32. Longest Valid Parentheses
- LeetCode Online Judge 题目C# 练习 - Longest Valid Parentheses
- LeetCode:Longest Valid Parentheses
- leetcode Longest Valid Parentheses
- LeetCode Longest Valid Parentheses
- Leetcode 之Longest Valid Parentheses(39)
- leetcode--Longest Valid Parentheses
- leetcode 32: Longest Valid Parentheses
- Leetcode: Longest Valid Parentheses