```
public int maximalSquare(char[][] matrix) {
if (matrix.length == 0) return 0;
int m = matrix.length, n = matrix[0].length, res = 0;
int[] dp = new int[n];
for (int i = 0; i < m; i++){
int diag = dp[0];
for (int j = 0; j < n; j++){
if (i == 0 || j == 0){
dp[j] = matrix[i][j] - '0';
}else{
int tmp = dp[j];
if (matrix[i][j] - '0' == 1)
dp[j] = Math.min(Math.min(dp[j-1], dp[j]), diag) + 1;
else
dp[j] = 0;
diag = tmp;
}
res = Math.max(res, dp[j]);
}
}
return res * res;
}
```