[Java] LeetCode32 Longest Valid Parentheses

來源:互聯網
上載者:User

標籤:leetcode

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.

題意:給定一串包含括弧的字串,求字長有效括弧串。能順序匹配的。這一題剛開始想好久~~,用stack來做題,很容易求出字串中所有有效括弧長度。但是如何求有效子串呢?如果我們能找出無效括弧的index,將有效index減去上一個無效的index,那麼就是該字元的有效子串。弄清楚這一點求最大的有效字串也會變得很容易。

 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);//我們變換思路,將括弧的index入棧            else            {               if(!stack.isEmpty()&&s.charAt(stack.peek())=='(')//如果是’)',且與stack頂括弧匹配時,彈出               {                   stack.pop();                   res=Math.max(stack.isEmpty()?i+1:i-stack.peek(),res);//為空白的話,證明前面沒有無效括弧,將i+1;不為空白的,前面有無效字元,減去無效字元的index               }else               {                   stack.push(i);               }            }            i++;        }       return res;     }



[Java] LeetCode32 Longest Valid Parentheses

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.