32. Longest Valid Parentheses *HARD*
Posted ArgenBarbie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了32. Longest Valid Parentheses *HARD*相关的知识,希望对你有一定的参考价值。
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(string s) { int maxLen = 0; int lastError = -1; vector<int> stack; for(int i=0; i<s.size(); i++) { if (s[i] == ‘(‘) stack.push_back(i); else if (s[i] == ‘)‘) { if (stack.size()>0 ) { stack.pop_back(); int len; if (stack.size()==0) len = i - lastError; else len = i - stack.back(); if (len > maxLen) maxLen = len; } else lastError = i; } } return maxLen; }
以上是关于32. Longest Valid Parentheses *HARD*的主要内容,如果未能解决你的问题,请参考以下文章