标签:
‘(‘
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.
The idea is to diminishing all “()” pairs. Keep the indices of unmatched ‘(‘ or ‘)’ in a stack. The difference between two indices of unmatched parenthesis is the length of a valid string in between.
class Solution { public int longestValidParentheses(String s) { int len = s.length(); int maxLen = 0; Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i < len; i++) { if (s.charAt(i) == ‘(‘) stack.push(i); else if (!stack.isEmpty() && s.charAt(stack.peek()) == ‘(‘) stack.pop(); else stack.push(i); } if (stack.isEmpty()) maxLen = len; else { int a = len, b; while (!stack.isEmpty()) { b = stack.pop(); maxLen = Math.max(maxLen, a - b - 1); a = b; } maxLen = Math.max(maxLen, a); } return maxLen; } }
DP Solution:
use a matches array to keep the max length of valid string. Do this only when you see ‘)‘.
class Solution { public int longestValidParentheses(String s) { int[] matches = new int[s.length()]; int open = 0; int max = 0; for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == ‘(‘) ++open; else if (open > 0) {// matches found matches[i] = 2 + matches[i - 1]; //add 2 each time because you found a pair. if (i > matches[i]) matches[i] += matches[i - matches[i]]; //append previous valid string --open; } if (matches[i] > max) max = matches[i]; } return max; } }
标签:
原文地址:http://www.cnblogs.com/neweracoding/p/5778481.html