Longest Valid Parentheses
Posted wxquare的学习笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Valid Parentheses相关的知识,希望对你有一定的参考价值。
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.
class Solution{ public: int longestValidParentheses(string s){ stack<int> lefts; // index of left parentheses. int len = s.length(); if(len < 2) return 0; int start = -1; int res = 0; for (int i=0;i<len;i++){ if(s[i] == ‘(‘){ lefts.push(i); }else{ if(lefts.empty()){ start = i; }else{ lefts.pop(); if(lefts.empty()){ res = max(res,i - start); }else{ res = max(res,i- lefts.top()); } } } } return res; } };
以上是关于Longest Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章