arshelia / algorithm-js

LeetCode 刷题
0 stars 0 forks source link

6.Z字形变换 #9

Open arshelia opened 4 years ago

arshelia commented 4 years ago

题目

链接:https://leetcode-cn.com/problems/zigzag-conversion/

arshelia commented 4 years ago

解法一

var convert = function(s, numRows) {
  let count = 0;
  let arr = [];
  let total = 0;
  while(total < s.length){
    let tempArr = new Array(numRows);
    if(count === 0){
      tempArr = s.substr(total, numRows);
      total += numRows;
    } else {
      tempArr[numRows-count-1] = s.substr(total,1);
      total += 1;
    }
    arr.push(tempArr);
    if(count < numRows - 2){
      count ++
    } else {
      count = 0;
    }
  }
  let result = '';
  for(let i = 0; i < numRows; i++){
    for(let j = 0; j < arr.length; j++){
      if(arr[j][i]){
        result = `${result}${arr[j][i]}`;
      }
    }
  }
  return result;
};
arshelia commented 4 years ago

解法二

var convert = function(s, numRows) {
  if(numRows < 2) return s;
  var res = new Array(numRows);
  for(let i = 0; i < numRows; i ++){
    res[i] = "";
  }
  let count = 0;
  flag = -1;
  for(let j = 0; j < s.length; j++){
    res[count] = `${res[count]}${s[j]}`;
    if(count === 0 || count === numRows -1) flag = -flag;
    count += flag;
  }
  let result = '';
  for(let i = 0; i < numRows; i++){
    result = `${result}${res[i]}`
  }
  return result;
};