본문 바로가기
코딩테스트(알고리즘)/leetCode

[leetCode] 6.Zigzag Conversion (Javascript)

by Cafe Mocha 2022. 6. 24.

(5) Zigzag Conversion - LeetCode

 

Zigzag Conversion - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com


접근 : 문자열 구현

 

Javascript

let input = require("fs")
  .readFileSync("input.txt") //"/dev/stdin"
  .toString()
  .split("\n")
  .map((val) => val.trim());

function solution(input) {
  //input
  let s = input[0];
  let num = +input[1];

  // Submit
  if (num === 1) {
    return s;
  }

  const len = s.length;
  const arr = [...Array(num)].map((r) => []);

  for (let i = 0; i < len; i++) {
    const pos = i % (2 * num - 2);
    const position = pos < num ? pos : 2 * num - 2 - pos;
    arr[position].push(s[i]);
  }
  // console.log(arr);
  return arr.map((r) => r.join("")).join("");
}

solution(input);