6.Z字形变换
链接:6.Z字形变换
难度:Medium
标签:字符串
简介:将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
题解 1 - javascript
- 编辑时间:2020-04-07
- 执行用时:92ms
- 内存消耗:42.5MB
- 编程语言:javascript
- 解法介绍:新建数组依次插入字符,通过字符在哪个位置插入来进行判断。
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
var convert = function (s, numRows) {
  if (numRows === 1) return s;
  let result = '';
  const arrs = new Array(numRows);
  for (let i = 0; i < numRows; i++) arrs[i] = [];
  function comp(i) {
    if (i < numRows) return i;
    const loop = numRows + numRows - 2;
    let num;
    do {
      num = i % loop;
    } while (num > loop);
    if (num < numRows) return num;
    else return loop - num;
  }
  for (let i = 0; i < s.length; i++) {
    arrs[comp(i)].push(s[i]);
  }
  for (const arr of arrs) {
    for (const s of arr) {
      if (s !== undefined) result += s;
    }
  }
  return result;
};
题解 2 - cpp
- 编辑时间:2022-03-01
- 执行用时:1060ms
- 内存消耗:9.1MB
- 编程语言:cpp
- 解法介绍:遍历后塞入数组。
class Solution {
   public:
    string convert(string s, int numRows) {
        if (numRows == 1) return s;
        char arr[1000][1000];
        memset(arr, 0, sizeof(char) * 1000 * 1000);
        for (int idx = 0, row = 0, col = 0, n = s.size(); idx < n;) {
            while (idx < n && row < numRows - 1) arr[row++][col] = s[idx++];
            while (idx < n && row > 0) arr[row--][col++] = s[idx++];
        }
        string ans = "";
        for (int i = 0; i < 1000; i++) {
            for (int j = 0; j < 1000; j++) {
                if (arr[i][j]) ans += arr[i][j];
            }
        }
        return ans;
    }
};