32. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
题意:求出最长的有效括号的长度
代码如下:
/** * @param {string} s * @return {number} */ var longestValidParentheses = function(s) { var stack=[]; var res=0,start=0; for(var i=0;i<s.length;i++){ if(s[i]==='('){ stack.push(i) }else if(s[i]===')'){ if(stack.length===0){ start=i+1; }else{ stack.length=stack.length-1; res=stack.length===0?Math.max(res,i-start+1):Math.max(res,i-stack[stack.length-1]); } } } return res; };