본문 바로가기
알고리즘/leetcode&프로그래머스

[LEETCODE] 6. ZigZag Conversion - javascript (풀이 있음)

by 윤-찬미 2021. 5. 9.

👀문제 - leetcode n.6 - medium

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

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)P A H N A P L S I I G Y I R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

 

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI"

Example 3:

Input: s = "A", numRows = 1 Output: "A"

 

Constraints:

  • 1 <= s.length <= 1000
  • s consists of English letters (lower-case and upper-case), ',' and '.'.
  • 1 <= numRows <= 1000

👀 문제풀이

이 문제는 문자열 s와  싸이클 텀인 numRows가 주어 진다.

아래와 같이 주어진 문자열 s를 numRows의 행에 따라 지그재그 모양으로 만들었을때 순서대로 출력하는 문제 이다.

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P     I    N
A   L S  I G
Y A   H R
P     I

문제의 핵심은 싸이클을 찾는 것이다.

 (numRows - 1 * 2) 의 싸이클에 따라 움직인다.

즉 문제 예시를 따르면 6의 싸이클이 만들어 진다는 이야기 이므로 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0. 1, 2 ............

와 같은 싸이클이 만들어 짐을 활용하여,

아래와 같이 각 행마다 들어가야할 문자열을 싸이클을 맞춰 넣어주면 된다는 이야기다.

var convert = function(s, numRows) {
  if (s.length <= numRows || numRows < 2) return s;
  const len = s.length;
  const num = 2 * (numRows - 1);
  let res = Array(numRows).fill('');
  let tmp = 0;
  for (let i = 0; i < len; i++) {
    tmp = i % num;
    if (tmp < numRows) {
      res[tmp] += s[i];
    } else {
      res[num - tmp] += s[i];
    }
  }
  return res.join('');
};

 

👀 후기

조금 고민하면 금방 풀 수 있는 문제라는 생각이 들었는데,

핵심은 싸이클을 찾아야 한다는 거다.

나는 이런 규칙을 도출해 내는게 약해서 좀 고민을 오래했다 ㅜㅜ 😹

알고리즘을 풀때는 저런 핵심 포인트를 찾아 푸는게 관점인데,

난 늘 직관적으로 그저 '문제 순서대로 구현'에 너무 치중 되어 있는 것 같다. 이런 걸 고치려면 더 많이 풀어봐야겠지.. ㅜㅜ