본문 바로가기
LeetCode/코딩 테스트 스터디 2주차

[LeetCode] 6. Zigzag Conversion 풀이 (JS)

by inwoo1324 2022. 7. 17.

0. 문제

https://leetcode.com/problems/zigzag-conversion/

 

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

문자열  "PAYPALISHIRING"  은 다음과 같이 주어진 행 수에 지그재그 패턴으로 작성된다.

P      A       H      N

A  P  L   S   I   I   G

Y       I       R

"PAHNAPLSIIGYIR" 을 한 줄씩 읽고 문자열로 반환하는 문제.

#1
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
#2
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
#3
Input: s = "A", numRows = 1
Output: "A"

 

1.언어

자바스크립트(JavaScript)

 

2. 문제 풀이

var convert = function(s, numRows) {
    let str_arr=Array(numRows).fill(''), 
            coord=0, dir=1; 
    
    if (numRows==1) return s
    
    for (let i of s){
        str_arr[coord]+=i;
        coord += dir;
        if (coord == numRows-1) dir = -1;
        else if (coord == 0) dir = 1;
    }
    
    return str_arr.reduce(function add(x,y){return x + y})
};
Runtime: 118 ms, faster than 67.12% of JavaScript online submissions for Zigzag Conversion.
Memory Usage: 46.4 MB, less than 77.71% of JavaScript online submissions for Zigzag Conversion.
 

P      A       H      N         str_arr[0] = 'PAHN'

A  P  L   S   I   I   G        str_arr[1] = 'APLSIIG'

Y       I       R                  str_arr[2] = 'YIR'

* 행 수 만큼 배열을 생성

* 반복문을 돌며 배열(str_arr[coord])에 문자를 더하고, coord에 dir를 더해준다.

* 변수 coord가 행 수를 만나면  dir = -1     변수 coord가 0를 만나면  dir = +1

* 마지막 배열의 모든 요소를 더해준 값을 반환한다.