Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions lcof2/剑指 Offer II 040. 矩阵中最大的矩形/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,57 @@ func largestRectangleArea(heights []int) int {
}
```

#### Swift

```swift
class Solution {
func maximalRectangle(_ matrix: [String]) -> Int {
guard let firstRow = matrix.first else {
return 0
}

let n = firstRow.count
var heights = [Int](repeating: 0, count: n)
var ans = 0

for row in matrix {
for (j, char) in row.enumerated() {
if char == "1" {
heights[j] += 1
} else {
heights[j] = 0
}
}
ans = max(ans, largestRectangleArea(heights))
}

return ans
}

private func largestRectangleArea(_ heights: [Int]) -> Int {
var res = 0
let n = heights.count
var stack = [Int]()
var left = [Int](repeating: -1, count: n)
var right = [Int](repeating: n, count: n)

for i in 0..<n {
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
right[stack.removeLast()] = i
}
left[i] = stack.isEmpty ? -1 : stack.last!
stack.append(i)
}

for i in 0..<n {
res = max(res, heights[i] * (right[i] - left[i] - 1))
}

return res
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
46 changes: 46 additions & 0 deletions lcof2/剑指 Offer II 040. 矩阵中最大的矩形/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
class Solution {
func maximalRectangle(_ matrix: [String]) -> Int {
guard let firstRow = matrix.first else {
return 0
}

let n = firstRow.count
var heights = [Int](repeating: 0, count: n)
var ans = 0

for row in matrix {
for (j, char) in row.enumerated() {
if char == "1" {
heights[j] += 1
} else {
heights[j] = 0
}
}
ans = max(ans, largestRectangleArea(heights))
}

return ans
}

private func largestRectangleArea(_ heights: [Int]) -> Int {
var res = 0
let n = heights.count
var stack = [Int]()
var left = [Int](repeating: -1, count: n)
var right = [Int](repeating: n, count: n)

for i in 0..<n {
while !stack.isEmpty && heights[stack.last!] >= heights[i] {
right[stack.removeLast()] = i
}
left[i] = stack.isEmpty ? -1 : stack.last!
stack.append(i)
}

for i in 0..<n {
res = max(res, heights[i] * (right[i] - left[i] - 1))
}

return res
}
}