1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

return 4
// O(mn) space
public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0) return 0;
        int m = matrix.length, n = matrix[0].length;
        // right-bottom corner of square, and its width
        int[][] dp = new int[m+1][n+1];
        int width = 0;
        for(int i=1; i<=m; i++){
            for(int j=1; j<=n; j++){
                if(matrix[i-1][j-1] == '1'){
                    dp[i][j] = Math.min(Math.min(dp[i-1][j], dp[i][j-1]), dp[i-1][j-1]) +1;
                    width = Math.max(width, dp[i][j]);
                } else dp[i][j] = 0;
            }
        }
        return width*width;
    }
}
// 只和上一层有关系,可以用O(n)空间,只记录上一层
public class Solution {
    public int maximalSquare(char[][] matrix) {
        if(matrix == null || matrix.length == 0) return 0;
        int m = matrix.length, n = matrix[0].length;
        // right-bottom corner of square, and its width
        int[] dp1 = new int[n+1];
        int width = 0;
        for(int i=0; i<m; i++){
            int[] dp2 = new int[n+1];
            for(int j=0; j<n; j++){
                if(matrix[i][j] == '1'){
                    dp2[j+1] = Math.min(Math.min(dp1[j], dp1[j+1]), dp2[j]) + 1;
                    width = Math.max(dp2[j+1], width);
                } else {
                    dp2[j+1] = 0;
                }
            }
            dp1 = dp2;
        }
        return width*width;
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。