Leetcode Longest Valid Parentheses report, validparentheses

Source: Internet
Author: User

Leetcode Longest Valid Parentheses report, validparentheses
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.
Https://oj.leetcode.com/problems/longest-valid-parentheses/
Analyze and obtain the length of the valid () pair in a string consisting of '(' and. For example: (), the result is 4. () The result is 6. () The result is 4.
Solution: the easiest way to solve the problem is to calculate the number of valid () strings between any two points (I to j). The results can be obtained through dynamic planning. Algorithm complexity:
To solve the problem of O (n), you need to understand the following situations:

The AC code is as follows:

public class Solution {    public int longestValidParentheses(String s) {        if(s==null||s.length()==0) {            return 0;        }        int start     = -1;        int maxLength = 0;        Stack stack   = new Stack();        for(int i=0;i<s.length();i++) {            if(s.charAt(i)=='(') {                stack.push(i);            } else {                if(!stack.empty()) {                    stack.pop();                    if(stack.empty()==true) {                        maxLength = Math.max(i - start , maxLength);                    } else {                        maxLength = Math.max(i - (int)stack.peek() , maxLength);                    }                } else {                    start = i;                }            }        }            return maxLength;    }}






Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.