class Solution {
public int maximalSquare(char[][] matrix) {
if(matrix.length==0) return 0;
int res= Integer.MIN_VALUE;
int [][] dp = new int[matrix.length+1][matrix[0].length+1];
for(int i=1;i<dp.length;i++){
for(int j=1;j<dp[0].length;j++){
if(matrix[i-1][j-1]=='1'){
int near = Math.min(dp[i-1][j],dp[i][j-1]);
dp[i][j] = 1+Math.min(near,dp[i-1][j-1]);
}
res = Math.max(res,dp[i][j]);
}
}
return res*res;
}
}
Solution 2:优化的DP
public class Solution {
public int maximalSquare(char[][] matrix) {
int rows = matrix.length, cols = rows > 0 ? matrix[0].length : 0;
int[] dp = new int[cols + 1];
int maxsqlen = 0, prev = 0;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= cols; j++) {
int temp = dp[j];
if (matrix[i - 1][j - 1] == '1') {
dp[j] = Math.min(Math.min(dp[j - 1], prev), dp[j]) + 1;
maxsqlen = Math.max(maxsqlen, dp[j]);
} else {
dp[j] = 0;
}
prev = temp;
}
}
return maxsqlen * maxsqlen;
}
}
Solution 1:正常的DPclass Solution { public int maximalSquare(char[][] matrix) { if(matrix.length==0) return 0; int res= Integer.MIN_VALUE; int [][] dp = new int[matrix.length...