bfe.dev 是一个针对前端的刷题网站,像是前端的LeetCode。该系列文章是我在上面的刷题日记。

题目9

BFE.dev#32 9. 解密消息

在一个字符串的二维数组中,有一个隐藏字符串。

I B C A L K A
D R F C A E A
G H O E L A D 

可以按照如下步骤找出隐藏消息

  1. 从左上开始,向右下前进
  2. 无法前进的时候,向右上前进
  3. 无法前进的时候,向右下前进
  4. 2和3的重复

无法前进的时候,经过的字符就就是隐藏信息。比如上面的二维数组的话,隐藏消息是IROCLED

注:如果没有的话,返回空字符串

分析

前进的时候实际上只有Y轴的方向会交替改变,我们可以用一个flag来表示其方向。

通过记录当前位置x, y,我们可以得到下一个未知x + 1, y + 1 或者 x + 1, y - 1

当遇到边界的时候,改变Y轴的方向,直到最后的元素被取到,就返回结果。

代码开始

代码实际上比较简单,就是上述分析的实现,不再赘述了。


/**
 * @param { string[][] } message
 * @returns { string }
 */
function decode(message) {
  // edge case
  const rows = message.length
  if (rows === 0) return ''
  const cols = message[0].length
  if (cols === 0) return ''
  
  let result = ''
  let i = 0
  let j = 0
  
  // keep track of the direction vertically
  let directionY = 1
  
  while (j < cols) {
    result += message[i][j]
    
    // switch direction at the border
    if (i === rows - 1) {
      directionY = -1
    }
    if (i === 0) {
      directionY = 1
    }
    
    i += directionY
    j += 1
  }
  
  return result
}

同时我把代码也放在了这里

通过,撒花!

如果你感兴趣,可以在 BFE.dev 上试试 https://bigfrontend.dev/zh/pr...

希望能有所帮助,下次再见! 前端刷题!走起!


JSer
12 声望3 粉丝

[链接]