利用滚动矩阵节省内存。
public class Solution {
public int maximalSquare(char[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int row = matrix.length;
int col = matrix[0].length;
int max = Integer.MIN_VALUE;
int[] square = new int[col];
int cache = 0;
for (int j = 0; j < col; j++) {
square[j] = Character.getNumericValue(matrix[0][j]);
max = Math.max(max, square[j]);
}
for (int i = 1; i < row; i++) {
cache = square[0];
square[0] = Character.getNumericValue(matrix[i][0]);
for (int j = 1; j < col; j++) {
if (matrix[i][j] == '1') {
int min = Math.min(square[j - 1], cache);
min = Math.min(min, square[j]);
cache = square[j];
square[j] = min + 1;
} else {
cache = square[j];
square[j] = 0;
}
max = Math.max(max, square[j]);
}
}
return max * max;
}
}