最长有效括号子串长度 c语言,LeetCode: 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.
翻譯:
給定一個包含‘(’和‘)’的字符串,找出最長的有效括號匹配子串的長度。
解法:
這道題可以用一維動態規劃逆向求解。假設輸入括號表達式為String s,維護一個長度為s.length的一維數組dp[],數組元素初始化為0。 dp[i]表示從s[i]到s[s.length - 1]最長的有效匹配括號子串長度。則存在如下關系:
dp[s.length - 1] = 0;
從i - 2 -> 0逆向求dp[],并記錄其最大值。若s[i] == '(',則在s中從i開始到s.length - 1計算s[i]的值。這個計算分為兩步,通過dp[i + 1]進行的(注意dp[i + 1]已經在上一步求解):
在s中尋找從i + 1開始的有效括號匹配子串長度,即dp[i + 1],跳過這段有效的括號子串,查看下一個字符,其下標為j = i + 1 + dp[i + 1]。若j沒有越界,并且s[j] == ‘)’,則s[i ... j]為有效括號匹配,dp[i] =dp[i + 1] + 2。
在求得了s[i ... j]的有效匹配長度之后,若j + 1沒有越界,則dp[i]的值還要加上從j + 1開始的最長有效匹配,即dp[j + 1]。
Java Code:
public class Solution {
public int longestValidParentheses(String s) {
// Start typing your Java solution below
// DO NOT write main() function
int n = s.length();
int[] dp = new int[n];
java.util.Arrays.fill(dp, 0);
int max = 0;
for (int i = n - 2; i >= 0; i--) {
if (s.charAt(i) == '(') {
int j = i + 1 + dp[i + 1];
if (j < n && s.charAt(j) == ')') {
dp[i] = dp[i + 1] + 2;
int k = 0;
if (j + 1 < n) {
k = dp[j + 1];
}
dp[i] += k;
}
max = Math.max(max, dp[i]);
}
}
return max;
}
}
總結
以上是生活随笔為你收集整理的最长有效括号子串长度 c语言,LeetCode: Longest Valid Parentheses (求最长有效匹配括号子串的长度)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python定时执行脚本实例
- 下一篇: CAN总线技术 | 物理层04 - 终端