4.1.2 Longest Valid Parentheses

Notes:
  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_1(string s) {
	stack<int> stk;
	int res = 0, count = 0;
	for (int i = 0; i < s.size(); ++i) {
		if (s[i] == '(') {
			stk.push(count);
			//count = 0;
		}
		else if (!stk.empty()) {
			count  = (1 + stk.top());
			stk.pop();
			res = max(res, count);
		}
		else {
			count = 0;
		}
	}
	return res * 2;
}


你可能感兴趣的:(4.1.2 Longest Valid Parentheses)