[LeetCode][Java] Longest Valid Parentheses

來源:互聯網
上載者:User

標籤:leetcode   java   longest valid parent   

題目:

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.

題意:

給定一個字串值包含字元‘(‘ and ‘)‘,找出最長有效括弧子串。

對於 "(()",最長有效子串為"()",長度為2.

另一個例子是")()())",其中的最長有效括弧子串為"()()",長度為4.

演算法分析:

  1. stack裡面裝的一直是“還沒配好對的那些可憐的括弧的index”
  2. 是’(‘的時候push
  3. 是’)‘的時候,說明可能配對了;看stack top是不是左括弧,不是的話,push當前右括弧
  4. 是的話,pop那個配對的左括弧,然後update res:i和top的(最後一個配不成對的)index相減,就是i屬於的這一段的當前最長。如果一pop就整個棧空了,說明前面全配好對了,那res就是最大=i+1

AC代碼:

public class Solution {    public int longestValidParentheses(String s)     {        int res = 0;        Stack<Integer> stack = new Stack<Integer>();        char[] arr = s.toCharArray();        for (int i = 0; i < arr.length; i++)         {            if (arr[i] == ')' && !stack.isEmpty() && arr[stack.peek()] == '(')             {                stack.pop();                if (stack.isEmpty())                    res = i + 1;                else                    res = Math.max(res, i - stack.peek());            }             else             {                stack.push(i);            }        }        return res;    }}


著作權聲明:本文為博主原創文章,轉載註明出處

[LeetCode][Java] 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.