標籤: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.
演算法分析:
- stack裡面裝的一直是“還沒配好對的那些可憐的括弧的index”
- 是’(‘的時候push
- 是’)‘的時候,說明可能配對了;看stack top是不是左括弧,不是的話,push當前右括弧
- 是的話,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