Index: [Leetcode] Leetcode indicator interpretation (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, assuming the match is out of the stack, and 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. can actually maintain () the length of the match. It is only
())) possible ((() to appear and the situation. So you have to sweep it over and over.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 very long time ago a solution, with too much space for Orz. Now it is 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; }};
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
[Leetcode] 032. Longest Valid parentheses (hard) (C + +)