Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
032. Longest Valid parentheses (hard)
links:
Title: https://oj.leetcode.com/problems/longest-valid-parentheses/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Ask the length of the longest legal parenthesis string in a
Analysis:
- (c + +) is done with a stack, and if the match is out of the stack, then the length is the
cur - stack_top_pos previous position of the match. O (n) time, O (n) space.
- (c + +) stack consumes too much space, in fact, can maintain () the length of the match, but may appear
())) and ((() the situation, so to sweep back and forth. O (n) time, O (1) space.
- With a more complex DP to do, but the space can not solve the solution 2 so excellent. Just saw me a long time ago a solution, with too much space Orz. Now it's 1 or 2 good practice.
Code:
Solution 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.pu SH (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;} ;
Solution 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 + +)