LeetCode Longest Valid Parentheses
class Solution { public: int longestValidParentheses(string s) { vector<int> stack; int maxlen = 0; int curlen = 0; int last = -1; int len = s.length(); for (int i=0; i<len; i++) { char ch = s[i]; if (ch == '(') { stack.push_back(i); continue; } if (stack.empty()) { last = i; continue; } stack.pop_back(); if (stack.empty()) { curlen = i - last; } else { curlen = i - stack.back(); } if (curlen > maxlen) 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<int> idx; while (pos<len) { char ch = s[pos]; if (ch == '(') { idx.push_back(pos); pos++; continue; } if (idx.empty()) { last_invalid = pos; pos++; continue; } idx.pop_back(); if (idx.empty()) { maxlen = max(maxlen, pos - last_invalid); } else { maxlen = max(maxlen, pos - idx.back()); } pos++; } return maxlen; } };