[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)
}