Skip to content

[Leetcode] 6. Zigzag Conversion โ€‹

Problem โ€‹

๋ฌธ์ œ ๋งํฌ

๋ฌธ์ž์—ด์—ด๊ณผ ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ์•„๋ž˜์˜ ํ˜•ํƒœ๋กœ ์ง€๊ทธ์žฌ๊ทธ๋กœ ๋ฐฐ์น˜ํ›„ ํ–‰์˜ ์ˆœ์„œ์˜ ๋งž๊ฒŒ ๋ฌธ์ž์—ด์„ ๋ฆฌํ„ด

js
P   A   H   N
A P L S I I G
Y   I   R

Solution โ€‹

ํ–‰์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฐฐ์—ด์„ ๋งŒ๋“ ๋‹ค. ๋ฐฐ์—ด์˜ ๊ฐ’์€ ๋นˆ ๋ฐฐ์—ด๋กœ ์ดˆ๊ธฐํ™”ํ•œ๋‹ค. ์ฒซ๋ฒˆ์งธ ํ–‰์—์„œ ๋งˆ์ง€๋ง‰ํ–‰๊นŒ์ง€ ๊ฐ’์„ ์ˆœ์ฐจ์ ์œผ๋กœ ๋„ฃ์–ด์ฃผ๊ณ  ํ–‰์„ ๋ฒ—์–ด๋‚˜๋ฉด ๋ฐ˜๋Œ€ ๋ฐฉํ–ฅ์œผ๋กœ ์ฐ์–ด์ฃผ๊ฒŒ ์กฐ๊ฑด์ฒ˜๋ฆฌํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

JS Code โ€‹

js
/**
 * @param {string} s
 * @param {number} numRows
 * @return {string}
 */
const convert = function (s, numRows) {
  const arr = Array.from(Array(numRows), () => ([]))

  let flag = 1
  let idx = 0

  for(const c of s) {
    if (idx < 0) idx++
    else if (numRows <= idx) idx--
    arr[idx].push(c)
    idx += flag
    if (numRows-1 === idx || 0 === idx) flag *= -1
  }

  return arr
    .flat()
    .reduce((acc,c) => acc+c)
}