forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximalrectangle.java
More file actions
executable file
·63 lines (52 loc) · 1.59 KB
/
maximalrectangle.java
File metadata and controls
executable file
·63 lines (52 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.Stack;
public class Solution {
public int maximalRectangle(char[][] matrix) {
// Start typing your Java solution below
// DO NOT write main() function
class Node{
int h;
int i;
Node(int h, int i){
this.h = h;
this.i = i;
}
}
if(matrix.length==0){
return 0;
}
int x = matrix.length;
int y = matrix[0].length;
int height[] = new int[y];
int max = 0;
Stack<Node> st = new Stack<Node>();
for(int i=0;i<x;i++){
for(int j=0;j<y;j++){
if(matrix[i][j]=='0'){
height[j]=0;
}
else{
height[j]++;
}
}
for(int j=0;j<y;j++){
if(st.empty() || st.peek().h < height[j]){
st.push(new Node(height[j],j));
}
else if(st.peek().h > height[j]){
int prev = 0;
while(!st.empty() && st.peek().h > height[j] ){
Node e = st.pop();
max = Math.max(max,(j-e.i)*e.h);
prev = e.i;
}
st.push(new Node(height[j],prev));
}
}
while(!st.empty()){
Node e = st.pop();
max = Math.max(max,(y-e.i)*e.h);
}
}
return max;
}
}