Longest Valid Parentheses 解答
Question
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.
Solution 1 -- Stack
Parenthese类的题目,第一反应是用栈。遇到'('入栈,遇到')'出栈。这题关键在于怎样知道当前的valid parenthese length。
我们用一个变量start来表示当前的第一个'(' 。
( ( ( ) ) ) ) ) (
start start
当栈为空时,进来的第一个左括号的位置为当前的start值。
出栈操作后:
1. 如果栈为空,说明从start开始的括号都匹配了。因此长度为 current - start + 1
2. 如果栈不为空,我们知道弹出栈的一定是都已经匹配了的。因此长度为 current - stack.peek()
因为只扫描了一遍原数组,所以时间复杂度是O(n),空间复杂度是O(n)
1 public class Solution { 2 public int longestValidParentheses(String s) { 3 if (s == null || s.length() < 1) { 4 return 0; 5 } 6 int length = s.length(); 7 Deque<Integer> stack = new LinkedList<Integer>(); 8 int start = 0; 9 int result = 0; 10 for (int i = 0; i < length; i++) { 11 char current = s.charAt(i); 12 if (current == '(') { 13 stack.push(i); 14 } else { 15 if (stack.isEmpty()) { 16 start = i + 1; 17 } else { 18 stack.pop(); 19 result = stack.isEmpty() ? Math.max(result, i - start + 1) : Math.max(result, i - stack.peek()); 20 } 21 } 22 } 23 return result; 24 } 25 }
Solution 2 -- DP