Topic:
Given A string containing just the characters ‘(‘ ‘)‘ and, find the length of the longest valid (well-formed) parenthe SES substring.
"(()"for, the longest valid parentheses substring "()" are, which has length = 2.
Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.
It means to find out the length of the longest brace match.
This problem also has a lot of reports, probably looked at a little, I see more is DP and use stack to do mark, all useful to O (N) space complexity. In fact, the spatial complexity of O (n) is unnecessary, and an O (n) time, O (1) space solution is proposed.
The main idea is that the positive sequence of each traversal of the "positive sequence needs to traverse, reverse order the worst need to traverse."
- Like (())) more than (the place is good to do, record the length of the previous match.)
- The problem is (() How to deal with (() where it is (always more), and how to find the strings that match the conditions. At this point, the reverse is needed to solve it, the actual is to eliminate the superfluous (.
- Before the reverse traversal of the string (more than), this string will only have one and must be at the end. Because: if there is a string like this, it has the ability to traverse backwards, that is, it can accommodate (and can accommodate).
- In turn, from the beginning, the length of the previous match is recorded directly in the (more) place that is unqualified. In this process, obviously each one will have (to match, find the strings that match the conditions in the string.)
- Finally, as many as possible (), that is, the end of the perfect match, the length of this time is also recorded, return the maximum length of the process.
The so-called record down is actually directly compared to the maximum length, updating the maximum length. The code is as follows:
public class Solution {public int longestvalidparentheses (String s) {int left = 0, len = 0, Tmpl = 0, pos = -1; for (int i = 0; I! = S.length (); i++) {if (S.charat (i) = = ' (') {left + +; Tmpl + +; }else{left--; if (left = =-1) {if (Tmpl > len) {len = Tmpl; } left = 0; Tmpl = 0; pos = i; }else{Tmpl + +; }}} if (Left > 0) {left = 0; tmpl = 0; for (int i = S.length ()-1; I! = pos; i--) {if (S.charat (i) = = ') ') {left + +; Tmpl + +; }else{left--; if (left = =-1) {if (Tmpl > len) {len = Tmpl; } left = 0; Tmpl = 0; }else{Tmpl + +; }}}} if (left = = 0) {if (Tmpl > len) len = Tmpl; } return len; }}
Leetcode:longest Valid parentheses O (n) time O (1) space