[Java] LeetCode32 longest Valid parentheses

Source: Internet
Author: User

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 is " () ", which has length = 2.

Another example ")()())" is, where the longest valid parentheses substring "()()" are, which has length = 4.

Test instructions: Given a string containing parentheses, find a valid word-length brace string. Can be matched in sequence. This problem has just begun to think for a long time ~ ~, with a stack to do the problem, it is easy to find all valid parentheses in the string length. But how do we find effective substrings? If we can find the index of the invalid parenthesis, subtract the valid index from the last invalid index, then it is the valid substring of the character. It is also easy to find the most effective string for this to be understood.

public int longestvalidparentheses (String s) {        if (s==null) return 0;        int len=s.length ();        int i=0;        Stack<integer> stack=new stack<integer> ();        char ch;        int res=0;        while (I<len)        {            Ch=s.charat (i);            if (ch== ' (')            stack.push (i);//We change the thinking, the index of the brackets into the stack            else            {               if (!stack.isempty () && S.charat (Stack.peek ()) = = ' (')//If ') ', and when matched with stack top bracket, pops               {                   stack.pop ();                   Res=math.max (Stack.isempty () I+1:i-stack.peek (), res);//null, proof that there is no invalid parenthesis in front, will be i+1; not empty, preceded by an invalid character, minus the invalid character's index               } else               {                   Stack.push (i);               }            }            i++;        }       return res;     }



[Java] LeetCode32 longest Valid parentheses

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.