DAY3-Zigzag Conversion[Level: Medium]
Jan 04, 2026
![DAY3-Zigzag Conversion[Level: Medium]](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog-custom%3Ftitle%3DLeetCode%2BDAY3%26tag%3DTemplate%2B1%26description%3DZigzag%2BConversion%255BLevel%253A%2BMedium%255D%26template%3D3%26backgroundImage%3Dhttps%253A%252F%252Fsource.inblog.dev%252Fog_image%252Fdefault.png%26bgStartColor%3D%2523ffffff%26bgEndColor%3D%2523ffffff%26textColor%3D%2523000000%26tagColor%3D%2523000000%26descriptionColor%3D%2523000000%26logoUrl%3Dhttps%253A%252F%252Fsource.inblog.dev%252Flogo%252F2025-12-24T06%253A07%253A46.034Z-ddf15b75-3608-41bd-8914-cd5d2d9efc83%26blogTitle%3D&w=3840&q=75)
문제.Zigzag Conversion
내 풀이 코드.
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function(s, numRows) {
if (numRows === 1 || s.length <= numRows) {
//numRows가 1거나 문자열길이가 행보다 작거나 같으면 그대로 리턴
return s;
}
const rows = Array(numRows).fill("")
let currentRowsIndex = 0
//글자를 넣을 rows의 현재 인덱스
let preTopDown = 0
//이전 꼭지점이 위였는지 아래였는지 0이면 index 0 1이면 인덱스 numRows - 1
for(let str = 0; str < s.length; str++){
if(preTopDown > 0){
rows[currentRowsIndex] += s[str]
currentRowsIndex --
}else {
rows[currentRowsIndex] += s[str]
currentRowsIndex ++
}
if(currentRowsIndex === numRows -1 ) preTopDown = 1
if(currentRowsIndex === 0 ) preTopDown = 0
}
return rows.join("")
};말로 푸는 코드 풀이.
주어진 행만큼의 배열을 빈 스트링으로 채워 준비함
Aray(numRows).fill(““)그다음은 주어진 문자열의 글자수만큼 돌면서 준비한 지그재그로 위치에 더해주어야 한다
넣을 배열내 index를 기억하고 → 코드내 currentRowsIndex
지그재그로 배열에 넣어야 하기때문에 내가지금 지그재그의 오르막인지 내리막인지를 기억해야한다 → 코드내 preTopDown
preTopDown이 0일경우를 오르막의 시작으로, preTopDown가 1일경우 내리막의 시작으로 정의한다
오르막일경우
rows[currentRowsIndex] += 현재요소를 넣어주고currentRowsIndex ++로 오르막길을 만들어 줌 반대일경우 —
반복이 모두 돈 후
rows.join("")으로 합친 문자로 리턴
Share article