LeetCode 题解工作台
统计水平子串和垂直子串重叠格子的数目
给你一个由字符组成的 m x n 矩阵 grid 和一个字符串 pattern 。 水平子串 是从左到右的一段连续字符序列。如果子串到达了某行的末尾,它将换行并从下一行的第一个字符继续。 不会 从最后一行回到第一行。 垂直子串 是从上到下的一段连续字符序列。如果子串到达了某列的底部,它将换列并从下一…
6
题型
0
代码语言
3
相关题
当前训练重点
中等 · 数组·string
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数组·string 题型思路
题目描述
给你一个由字符组成的 m x n 矩阵 grid 和一个字符串 pattern。
水平子串 是从左到右的一段连续字符序列。如果子串到达了某行的末尾,它将换行并从下一行的第一个字符继续。不会 从最后一行回到第一行。
垂直子串 是从上到下的一段连续字符序列。如果子串到达了某列的底部,它将换列并从下一列的第一个字符继续。不会 从最后一列回到第一列。
请统计矩阵中满足以下条件的单元格数量:
- 该单元格必须属于 至少 一个等于
pattern的水平子串,且属于 至少 一个等于pattern的垂直子串。
返回满足条件的单元格数量。
示例 1:
输入: grid = [["a","a","c","c"],["b","b","b","c"],["a","a","b","a"],["c","a","a","c"],["a","a","b","a"]], pattern = "abaca"
输出: 1
解释:
"abaca" 作为一个水平子串(蓝色)和一个垂直子串(红色)各出现一次,并在一个单元格(紫色)处相交。
示例 2:
输入: grid = [["c","a","a","a"],["a","a","b","a"],["b","b","a","a"],["a","a","b","a"]], pattern = "aba"
输出: 4
解释:
上述被标记的单元格都同时属于至少一个 "aba" 的水平和垂直子串。
示例 3:
输入: grid = [["a"]], pattern = "a"
输出: 1
提示:
m == grid.lengthn == grid[i].length1 <= m, n <= 10001 <= m * n <= 1051 <= pattern.length <= m * ngrid和pattern仅由小写英文字母组成。
解题思路
方法一
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the rolling hash implementation, typically O(m _n) for scanning all rows and columns. Space complexity is O(m_ n) to store match coordinates for horizontal and vertical occurrences. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Are you considering pattern matching optimization for large grids?
- question_mark
Can you handle wrapping logic in both horizontal and vertical directions efficiently?
- question_mark
How will you track overlapping cells without redundant computation?
常见陷阱
外企场景- error
Forgetting to wrap rows or columns correctly when scanning substrings.
- error
Counting a cell multiple times if it appears in multiple matches in one orientation.
- error
Ignoring edge cases when pattern length exceeds row or column segments.
进阶变体
外企场景- arrow_right_alt
Count cells for multiple patterns simultaneously using the same rolling hash approach.
- arrow_right_alt
Modify the grid to allow toroidal wrapping and count overlapping cells under new rules.
- arrow_right_alt
Count overlapping cells only for non-overlapping horizontal and vertical substrings.