JavaScript需求:在二维数组中查找垂直连续的指定单词
实现二维数组中垂直双向匹配指定单词的JavaScript函数
没问题,我来帮你搞定这个需求!下面是具体的实现思路、完整代码和测试示例:
核心思路
- 我们需要针对二维数组的每一列进行检查,因为是垂直方向的匹配
- 对每一列分别验证两个方向:
- 从上到下:依次对比列中连续的字符是否和目标单词顺序一致
- 从下到上:从列的末尾开始往上,对比连续字符是否和目标单词顺序一致
- 只要任意一列满足其中一个方向的匹配,就立即返回
true;遍历完所有列都没匹配到则返回false
完整实现代码
function findVerticalWord(grid, word) { const wordLength = word.length; const rows = grid.length; // 边界处理:如果网格行数比单词长度小,直接返回false(不可能有足够的连续字符) if (rows < wordLength) return false; // 处理空网格的情况 const cols = grid[0]?.length || 0; // 遍历每一列 for (let col = 0; col < cols; col++) { // 检查【从上到下】的匹配 let topToBottomMatch = true; for (let i = 0; i < wordLength; i++) { if (grid[i][col] !== word[i]) { topToBottomMatch = false; break; } } if (topToBottomMatch) return true; // 检查【从下到上】的匹配 let bottomToTopMatch = true; for (let i = 0; i < wordLength; i++) { // 从最后一行开始,往上偏移i个位置 const targetRow = rows - 1 - i; if (grid[targetRow][col] !== word[i]) { bottomToTopMatch = false; break; } } if (bottomToTopMatch) return true; } // 所有列都未匹配到目标单词 return false; }
测试示例
你可以用下面的例子验证函数的效果:
// 测试1:从上到下匹配apple const grid1 = [ ['a', 'b', 'c'], ['p', 'x', 'y'], ['p', 'm', 'n'], ['l', 'z', 'o'], ['e', 'k', 'r'] ]; console.log(findVerticalWord(grid1, 'apple')); // 输出: true // 测试2:从下到上匹配apple const grid2 = [ ['e', 'b', 'c'], ['l', 'x', 'y'], ['p', 'm', 'n'], ['p', 'z', 'o'], ['a', 'k', 'r'] ]; console.log(findVerticalWord(grid2, 'apple')); // 输出: true // 测试3:行数不足,无法匹配 const grid3 = [ ['a', 'b'], ['p', 'x'] ]; console.log(findVerticalWord(grid3, 'apple')); // 输出: false // 测试4:无匹配情况 const grid4 = [ ['a', 'x'], ['q', 'p'], ['p', 'l'], ['l', 'e'], ['e', 'a'] ]; console.log(findVerticalWord(grid4, 'apple')); // 输出: false
内容的提问来源于stack exchange,提问作者lupu51nfactum N778
相关产品推荐
相关产品推荐

