标签:dynamic programming 动态规划 leetcode parentheses
【题目】
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.
题意:给定一个包含左右括号的字符串,找出其中最长的有效子串,返回其长度。
思路:动态规划。用一个数组len[i]记录以i结尾的最长有效子串长度,如")()())"的动规数组为[0, 0, 2, 0, 4, 0]。具体做法是,从前往后遍历数组,遇到左括号,len[i]=0,遇到右括号,就往前找第一个多余的左括号的位置。首先跳过i前面的有效连续子串,碰到第一个没有匹配的括号p,如果p是右括号,那么p和i无法匹配,len[p]=0;如果p是左括号,那么p刚好和i匹配,此时要p到i都是有效子串,同时还要加上p前面连续的有效子串。
【Java代码】
public class Solution { public int longestValidParentheses(String s) { int longest = 0; int[] len = new int[s.length()]; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == '(') { len[i] = 0; } else { // find the nearest parentheses before i that not matched int p = i - 1; while (p >= 0 && len[p] > 0) { p -= len[p]; } // if p is left parentheses, then it mathches i if (p >= 0 && s.charAt(p) == '(') { len[i] = i - p + 1; // add the length that matched before p if (p > 0) { len[i] += len[p - 1]; } // update the parentheses length longest = Math.max(longest, len[i]); } } } return longest; } }
【LeetCode】Longest Valid Parentheses 解题报告
标签:dynamic programming 动态规划 leetcode parentheses
原文地址:http://blog.csdn.net/ljiabin/article/details/44904355