class Solution {public: int longestValidParentheses(string s) { vector stack; int maxlen = 0; int curlen = 0; int last = -1; int len = s.length(); for (int i=0; imaxlen) maxlen = curlen; } return maxlen; }};
参考:http://www.cnblogs.com/zhuli19901106/p/3547419.html
last用来记录最后一个无法匹配的右括号的位置,当stack为空时,必然存在一个合法的括号序列,而这个序列的起始肯定是last后面的一个位置。
智商有限,做了好久,只有看答案了。。。
第二轮:
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) { int len = s.size(); if (len < 2) return 0; int last_invalid = -1; int pos = 0; int maxlen = 0; vector idx; while (pos