32. Longest Valid Parentheses

来源:互联网 发布:百强家具怎么样知乎 编辑:程序博客网 时间:2024/05/06 03:31

Longest Valid 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.

思路:

使用动态规划DP:
  建立一个空数组长度为给定的字符串n 依次对应给定的字符串字符 然后通过计算得到每位字符所对应的值
(( ) ( )( ( )
0 0 2 0 4 0 0 6
下面的代码很好,程序运行复杂度也很小2ms,此算法非常值得参考

代码

public class Solution{    public int longestValidParentheses(String s) {        int n = s.length(), max = 0;        int[] matched = new int[n]; //建立一个数组        for (int right = 1; right < n; right++) {            if (s.charAt(right) == ')') { //注意从1开始,先检测右边‘)’的值                int left = right - 1 - matched[right - 1];  //检测到以后,计算与之相对应的左边的‘(’的位置                if (left >= 0 && s.charAt(left) == '(') {                    matched[right] = matched[right - 1] + 2; //得到每次()的长度                    if (left - 1 > 0)                        matched[right] += matched[left - 1]; //需累计算出有效长度                }            }            max = max <= matched[right] ? matched[right] : max; //得出最大的值        }    return max;    }}
0 0
原创粉丝点击