给你一个只包含 '(' 和 ')' 的字符串,找出最长有效(格式正确且连续)括号子串的长度。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Scanner; class Solution { public int longestValidParentheses(String s) { if (s == null || s.length() == 0) { return 0; } int ret = 0; int[] dp = new int[s.length()]; for (int i = 1; i < s.length(); ++i) { if (s.charAt(i) == ')') { int index = i - dp[i - 1] - 1; if (index >= 0 && s.charAt(index) == '(') { dp[i] = dp[i - 1] + 2; if (index - 1 >= 0) { dp[i] += dp[index - 1]; } } ret = Math.max(ret, dp[i]); } } return ret; } public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { System.out.println(new Solution().longestValidParentheses(in.next())); } } }