classSolution{ publicintmaximalRectangle(char[][] matrix){ //初始化int数组 int height = matrix.length; if(height==0){ return0; } int width = matrix[0].length; int[][] temp = newint[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { char ch = matrix[i][j]; int t = ch == '0' ? 0 : 1; if (i == 0) { temp[i][j] = t; } else { if (matrix[i - 1][j] == '0') { temp[i][j] = t; } else { if (t == 0) { temp[i][j] = 0; } else { temp[i][j] = t + temp[i - 1][j]; } } } } } //遍历每个数组求最大值 int max = 0; for (int i = 0; i < height; i++) { int t = getMaxArea(temp[i]); max = max > t ? max : t; } return max; }
publicintgetMaxArea(int[] array){ int len = array.length; if (len == 0) { return0; } int max = 0; Stack<Integer> stack = new Stack<>(); for (int i = 0; i < len; i++) { if (stack.isEmpty()) { stack.push(i); } else { int current = array[i]; if (current > array[stack.peek()]) { stack.push(i); } else { while (!stack.isEmpty() && current <= array[stack.peek()]) { int height = array[stack.pop()]; int start = -1; if (!stack.isEmpty()) { start = stack.peek(); } int area = height * (i - start - 1); max = max > area ? max : area; } stack.push(i); } } } if (!stack.isEmpty()) { int end = stack.peek(); while (!stack.isEmpty()) { int height = array[stack.pop()]; int start = -1; if (!stack.isEmpty()) { start = stack.peek(); } int area = height * (end - start); max = max > area ? max : area; } } return max; } }