LeetCode刷题日志#5:Z 字形变换

题目:传送门
类别:字符串
难度:中等

思路

这题也没啥算法,就是观察,总结数学规律。核心就是一个描述字符位置的函数。

代码

/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
  if (numRows === 1) {
    return s;
  }

  const groupSize = 2 * numRows - 2;
  const groupNum = Math.ceil(s.length / groupSize);

  const strArr = [];

  for (let i = 0, len = s.length; i < len; i++) {
    const char = s[i];
    const index = getIndex(i, groupNum, groupSize, numRows);
    strArr[index] = char;
  }

  return strArr.join('');
};

function getIndex(i, groupNum, groupSize, numRows) {
  const groupIndex = Math.floor(i / groupSize);
  const groupInnerIndex = i % groupSize;
  if (groupInnerIndex === 0) {
    return groupIndex;
  }
  if (groupInnerIndex === numRows - 1) {
    return groupNum + 2 * (numRows - 2) * groupNum + groupIndex;
  }
  
 
  if (groupInnerIndex < numRows - 1) {
    return groupNum + 2 * (groupInnerIndex - 1) * groupNum + groupIndex * 2;
  }

  const groupInnerIndex2 = 2 * numRows - 2 - groupInnerIndex;
  return groupNum + 2 * (groupInnerIndex2 - 1) * groupNum + groupIndex * 2 + 1;
}

评论

暂无评论