Leetcode32 Longest Valid Parentheses
2015-07-28 01:42
302 查看
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.
Solution1
这种题其实没有什么诀窍,多举几个实例渐渐归纳出一些规律出来。这里用栈来实现:import java.util.Stack; public class Solution { public int longestValidParentheses(String s) { Stack<Integer> stack = new Stack<Integer>(); int result = 0; for(int i=0,start=0;i<s.length();i++){ char c = s.charAt(i); if(c=='(') stack.push(i);//将左括号的位置都记录下来 else{ if(stack.empty()) start = i+1;//更新有可能成为最左边边界的位置 else{ stack.pop(); if(stack.empty()) result = Math.max(result,i-start+1);//说明已经和最左边边界连通起来了 else result = Math.max(result,i-stack.peek());//未和最左边边界连通,但是可以和之前的某个左括号组成有效的括号对 } } } return result; } }
Solution2
解法2和解法1思路是一致的,只不过用了更加巧妙的办法使得程序更简短,但是理解起来其实更加复杂了。import java.util.Stack; public class Solution { public int longestValidParentheses(String s) { Stack<Integer> stack = new Stack<Integer>(); int result = 0; for(int i=0,start=0;i<s.length();i++){ if(s.charAt(i)==')'&&!stack.empty()&&s.charAt(stack.peek())=='('){ stack.pop(); result = Math.max(result,i-(stack.empty()?-1:stack.peek())); }else stack.push(i);//这里相当于将解法一的start位置也存入了stack } return result; } }
Solution3
动态规划的解法。import java.util.Stack; public class Solution { public int longestValidParentheses(String s) { int n = s.length(); int[] dp = new int ; int left = 0, result = 0; for(int i=0;i<n;i++){ if(s.charAt(i)=='(') left++;//记录当前还有多少左括号未配对 else if(left>0){//若当前有左括号可与当前的右括号配对 dp[i] = 2 + dp[i-1];//先将这个配对的左括号计入 if(i-dp[i]>=0) dp[i] += dp[i-dp[i]];//判断是否和之前的左括号连通了 left--;//未配对左括号数减一 } result = Math.max(result,dp[i]); } return result; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解