首页 > 代码库 > Leetcode Longest Valid Parentheses 结题报告
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.
https://oj.leetcode.com/problems/longest-valid-parentheses/
分析,求出一串由:‘(’和‘)’组成的字符串中合法()配对的长度。例如:(()(),结果是4。((()))结果是6。())()()结果是4。
解题思路:最容易想到的解法就是穷举法,计算任意两点(i到j)之间有多少个合法的()串,借助动态规划可以得到结果。算法复杂度为:
想要O(n)的解法需要一点技巧,也要弄清楚几种情况:
AC代码如下所示:
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.
https://oj.leetcode.com/problems/longest-valid-parentheses/
分析,求出一串由:‘(’和‘)’组成的字符串中合法()配对的长度。例如:(()(),结果是4。((()))结果是6。())()()结果是4。
解题思路:最容易想到的解法就是穷举法,计算任意两点(i到j)之间有多少个合法的()串,借助动态规划可以得到结果。算法复杂度为:
想要O(n)的解法需要一点技巧,也要弄清楚几种情况:
AC代码如下所示:
public class Solution { public int longestValidParentheses(String s) { if(s==null||s.length()==0) { return 0; } int start = -1; int maxLength = 0; Stack stack = new Stack(); for(int i=0;i<s.length();i++) { if(s.charAt(i)=='(') { stack.push(i); } else { if(!stack.empty()) { stack.pop(); if(stack.empty()==true) { maxLength = Math.max(i - start , maxLength); } else { maxLength = Math.max(i - (int)stack.peek() , maxLength); } } else { start = i; } } } return maxLength; } }
Leetcode Longest Valid Parentheses 结题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。