标签:sequence 长度 amp else tps tput parent 括号 max
1.最长递增子序列问题
https://leetcode.com/problems/longest-increasing-subsequence/
public int lengthOfLIS(int[] nums) { if(nums.length==0||nums==null) return 0; int[] dp=new int[nums.length]; int max=0; for(int i=0;i<nums.length;i++) { dp[i]=1; for(int j=0;j<i;j++) { if(nums[i]>nums[j]){ dp[i]=Math.max(dp[j]+1,dp[i]); } } if(dp[i]>max) max=dp[i]; } return max; }
2.最长回文串问题
https://leetcode.com/problems/longest-palindromic-substring/
public String longestPalindrome(String s) { if(s==null||s.length()==0) return s; int[][] dp=new int[s.length()][s.length()]; int left=0,right=0,maxLen=1; for(int i=0;i<s.length();i++){ dp[i][i]=1; for(int j=i-1;j>=0;j--){ if(s.charAt(i)==s.charAt(j)&&(i-j==1||dp[j+1][i-1]!=0)) dp[j][i]=1; else dp[j][i]=0; if(dp[j][i]!=0&&i-j+1>=maxLen) { left=j; right=i; maxLen=i-j+1; } } } return s.substring(left,right+1); }
3.最长的有效括号的长度
Input: ")()())
"
Output: 4
https://leetcode.com/problems/longest-valid-parentheses/
public int longestValidParentheses(String s) { if(s==null||s.length()==0) return 0; Stack<Integer> stack=new Stack<>(); int start=0,maxLen=0; for(int i=0;i<s.length();i++) { if(s.charAt(i)==‘(‘) stack.push(i);//保存下标 else if(s.charAt(i)==‘)‘) { if(stack.isEmpty()) start=i+1;//直接跳过这一位,始终保持能够匹配的最左边的下标 else { stack.pop();//匹配弹出 maxLen=stack.isEmpty()?Math.max(maxLen, i-start+1):Math.max(maxLen, i-stack.peek()); } } } return maxLen; }
标签:sequence 长度 amp else tps tput parent 括号 max
原文地址:https://www.cnblogs.com/smallJunJun/p/10434631.html