https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-by-leetcode-solution
栈中只保存左括号的下标,每遍历到右括号就出栈,比较当前最大合法长度。
class Solution {
public:
int longestValidParentheses(string s) {
int maxLen = 0;
stack stk;
stk.push(-1); //栈中需要一个元素垫底
for (int i = 0; i < s.size(); i ++ )
{
if (s[i] == '(') stk.push(i); //只让左括号的下标进栈
else
{
stk.pop();
if (stk.empty()) stk.push(i);
else maxLen = max(maxLen, i - stk.top());
}
}
return maxLen;
}
};
作者:wo-yao-chu-qu-luan-shuo
链接:https://leetcode-cn.com/problems/longest-valid-parentheses/solution/zui-chang-you-xiao-gua-hao-zhan-by-wo-ya-s8og/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。