索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github:
https://github.com/illuz/leetcode
题目:https://oj.leetcode.com/problems/longest-valid-parentheses/
代码(github):https://github.com/illuz/leetcode
问一个字符串里最长的合法括号串的长度。
cur - stack_top_pos
也就是 - 匹配的前一个位置。 O(n) time, O(n) space。()))
和
((()
的情况,所以要前后各扫一遍。O(n) time, O(1) space。解法 1:(C++)
class Solution { public: int longestValidParentheses(string s) { stack<int> lefts; int max_len = 0, match_pos = -1; // position of first // matching '(' - 1 for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') lefts.push(i); else { if (lefts.empty()) // no matching left match_pos = i; else { // match a left lefts.pop(); if (lefts.empty()) max_len = max(max_len, i - match_pos); else max_len = max(max_len, i - lefts.top()); } } } return max_len; } };
解法 2:(C++)
class Solution { public: int longestValidParentheses(string s) { int max_len = 0, depth = 0, start = -1; // solve ((() for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') ++depth; else { --depth; if (depth == 0) max_len = max(max_len, i - start); else if (depth < 0) { start = i; depth = 0; } } } // solve ())) depth = 0; start = s.size(); for (int i = s.size(); i >= 0; --i) { if (s[i] == ')') ++depth; else { --depth; if (depth == 0) max_len = max(max_len, start - i); else if (depth < 0) { start = i; depth = 0; } } } return max_len; } };
[LeetCode] 032. Longest Valid Parentheses (Hard) (C++)
原文地址:http://blog.csdn.net/hcbbt/article/details/44242219