๋ฌธ์ ๋งํฌ
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
์ผ๋ฐ์ ์ธ ํํ์ ๋ฌธ์์ด ("ABCDEFG")์ ์ง๊ทธ์ฌ๊ทธ ํํ๋ก ๋ณํํ๊ณ ์ด๋ฅผ row ๊ธฐ์ค์ผ๋ก ์ฌ์ ๋ ฌํ๋ฉด ์ด๋ป๊ฒ ๋ณํ๋์ง ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
์ ๊ทผ ๋ฐฉ๋ฒ
์ง๊ทธ์ฌ๊ทธ๋ก ๋ณํ ํํ๋ฅผ index๋ฒํธ๋ก ๋ฐ๊ฟ ์ ์ด๋ณด๋ฉด ํจํด์ด ๋ณด์ธ๋ค. (numRows = 4์ผ๋)
0 6 12
1 5 7 11
2 4 8 10
3 9
ํ๋ฒ์ ์ํ์ด ์ด๋ค์ง๋๋ง๋ค (numRows - 1) * 2 ๊ฐ์ ์์๊ฐ ๋ฐ๋ณต๋๋ค.
0,1,2,3,4,5 -> 6,7,8,9,10,11 - > ...
์ด๋ฅผ ํตํด numRows ๊ธธ์ด์ ๋น ๋ฌธ์์ด ๋ฐฐ์ด์ ๋ง๋ค๊ณ index์ ๋ง์ถฐ ์ฝ์ ํ๋ฉด ํด๊ฒฐ๋๋ค.
0 -> 0๋ฒ index -> i % (numRows - 1) * 2
1 -> 1๋ฒ index -> i % (numRows - 1) * 2
2 -> 2๋ฒ index -> i % (numRows - 1) * 2
3 -> 3๋ฒ index -> i % (numRows - 1) * 2
4 -> 2๋ฒ index -> ((numRows - 1) * 2) - ( i % (numRows - 1) * 2 )
5 -> 1๋ฒ index -> ((numRows - 1) * 2) - ( i % (numRows - 1) * 2 )
6 -> ๋๊ฐ์ด ๋ฐ๋ณต
// ์ผ๋ฐ์ ์ธ ๋ฌธ์์ด s๋ฅผ ์ง๊ทธ์ฌ๊ทธ ํํ๋ก ๋ฐ๊ฟจ์๋ ๋ณํ๋๋ ๋ฌธ์์ด์ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
/**
* @param {string} s
* @param {number} numRows
* @return {string}
*/
var convert = function (s, numRows) {
let answer = new Array(numRows).fill('');
let patternLen = (numRows - 1) * 2;
if (numRows < 2) return s;
for (let i = 0; i < s.length; i++) {
let patternidx = i % patternLen;
if (patternidx < numRows) answer[patternidx] += s[i];
else answer[patternLen - patternidx] += s[i];
}
return answer.join('');
};
'์ฝ๋ฉํ ์คํธ > LeetCode' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 3Sum (0) | 2022.06.23 |
---|---|
[LeetCode] Furthest Building You Can Reach (0) | 2022.06.21 |
[LeetCode] search-suggestions-system (0) | 2022.06.19 |
[LeetCode] Longest Substring without Repeating Characters (0) | 2022.06.17 |
[LeetCode] binary Tree Cameras (0) | 2022.06.17 |