-
leetCode - ZigZag Conversion프로그래밍/algorithm 2021. 7. 19. 07:44
문제
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" Explanation: P I N A L S I G Y A H R P I
Example 3:
Input: s = "A", numRows = 1 Output: "A"
풀이
1. 결과를 담을 배열 result를 만들자.
2. result 배열 중 어느 인덱스에 문자를 담을 지 결정하기 위해서 index와 step이라는 변수를 사용한다.
3. index === 0 일 때는, 시작이기 때문에 step = 1로 해준다.
4. index === numRow-1일때는 step = -1로 바꿔줘서, 뒤 돌아가게 해준다.
const convert = function (s, numRows) { let result = []; let index = 0, step = 0; for (let i = 0; i < s.length; i++) { if (!result[index]) result[i] = ''; result[index] += s[i]; if (index === 0) { step = 1; } else if (index === numRows - 1) { step = -1; } index += step; } return result.join(''); };
'프로그래밍 > algorithm' 카테고리의 다른 글
leetCode - Regular Expression Matching (0) 2021.07.19 leetCode - Reverse Integer (0) 2021.07.19 leetCode - Longest Palindromic Substring(DP) (0) 2021.07.16 leetCode-Median of Two Sorted Arrays(binary search) (0) 2021.07.15 leetCode - Longest Substring Without Repeating Characters(LinkedList) (0) 2021.07.14