2023-03-19 力扣6 N字型变换

2023-03-18  本文已影响0人  爱玩游戏的iOS菜鸟
// 将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

// 方法一:模拟矩阵输出
var convert1 = function (s, numRows) {
  const length = s.length;
  const row = numRows;
  if (length === 1 || row === 1 || row >= length) {
    return s;
  }
  const recycle = row * 2 - 2; /// 代表一个周期多少字符
  const c = Math.floor((length + recycle - 1) / recycle) * (row - 1); /// 总共需要占用多少列  length + recycle -1 的原因是确保想下取整刚好正确
  const tempArray = new Array(row)
    .fill(0)
    .map(() => new Array(c).fill(0));
  for (let i = 0, x = 0, y = 0; i < s.length; i++) {
    tempArray[x][y] = s[i];
    if (i % recycle < row - 1) {
      x++; // 向下移动
    } else {
      x--; // 右上方移动
      y++;
    }
  }
  const newArr = [];
  for (const row of tempArray) {
    for (const item of row) {
      if (item !== 0) {
        newArr.push(item);
      }
    }
  }
  return newArr.join("");
};
// 方法二:矩阵空间优化
var convert2 = function (s, numRows) {
  const length = s.length;
  const row = numRows;
  if (length === 1 || row === 1 || row >= length) {
    return s;
  }
  const tempArr = new Array(row).fill(0)
  for (let i = 0; i < row; i++) {
    tempArr[i] = []
  }
  const t= row * 2 - 2
  for (let i = 0, x = 0; i < s.length; i++) {
    tempArr[x].push(s[i])
    if (i % t < row - 1) {
      x++
    } else {
      x--
    }
  }
  const newArr = []
  for (const row of tempArr) {
    newArr.push(row.join(''))
  }
  return newArr.join('')
};
上一篇 下一篇

猜你喜欢

热点阅读