动态规划(其他)
1,.计算最大1的面积
https://leetcode.com/problems/maximal-rectangle/
public int maximalRectangle(char[][] matrix) { if(matrix==null||matrix.length==0) return 0; int[] height=new int[matrix[0].length]; int res=0; for(int i=0;i<matrix.length;i++) { for(int j=0;j<matrix[i].length;j++) { height[j]=matrix[i][j]=='0'?0:height[j]+1; } res=Math.max(res, helper1(height));//从第一行依次往下累计比较 } return res; } //求直方图的最大面积 public int helper1(int nums[]) { int[] tempnums=new int[nums.length+1]; for(int i=0;i<nums.length;i++) tempnums[i]=nums[i]; tempnums[nums.length]=0; Stack<Integer> stack=new Stack<>();//栈保存的是下标,而且栈里面保存的一定是高度递增的下标,有些题和这种思想比较像 stack.push(0); int res=0; for(int i=1;i<tempnums.length;i++) { if(stack.isEmpty()||tempnums[i]>=tempnums[stack.peek()]) stack.push(i); else { int temp=stack.pop(); res=Math.max(res, tempnums[temp]*(stack.isEmpty()?i:i-stack.peek()-1)); --i; } } return res; }
2.正则匹配:
https://leetcode.com/problems/regular-expression-matching/description/
public boolean isMatch(String s, String p) {//p是模式串,s是待匹配的串 //p是模式串 //dp[i][j]表示s的前i个字符与p的前j个字符是否匹配,dp[0][0]代表空字符串 boolean[][] dp=new boolean[s.length()+1][p.length()+1]; dp[0][0]=true; for(int i=1;i<=s.length();i++) dp[i][0]=false; for(int j=1;j<=p.length();j++) { //从第二个字符开始比较,只有A*或者.*这种情况可以匹配空字符串,然后如果连续的这种情况就要看前一轮就是dp[0][i-2]的值 dp[0][j]=j>1&&'*'==p.charAt(j-1)&&dp[0][j-2]; } for(int i=1;i<=s.length();i++) for(int j=1;j<=p.length();j++) { if(p.charAt(j-1)=='*') { //模式串当前位为*,首先比较模式串往前两位,比如AB,AB*A*其实是匹配的,匹配dp[i][j-2] //模式串往前一位等于当前字符串更新dp[i][j]为dp[i-1][j]比如ABC|ABC*或者ABC|AB.*就可以更新为AB|ABC*和AB|AB.* dp[i][j]=dp[i][j-2]||((s.charAt(i-1)==p.charAt(j-2) || p.charAt(j-2)=='.')&&dp[i-1][j]); } else { //当前字符完全匹配,可以传递dp[i-1][j-1]的值 dp[i][j]=(p.charAt(j-1)=='.'||p.charAt(j-1)==s.charAt(i-1))&&dp[i-1][j-1]; } } return dp[s.length()][p.length()]; }
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/10654599.html

浙公网安备 33010602011771号