실수가 좀 잦은 것 같다.
numRows 내에서 첫줄과 마지막줄은 고정 크기만큼 jump 가 가능하며
그 중간에서의 Jump size만 계산하면 되는 문제다.
근데 Jump Size가 0으로 나오는 경우를 처리하지 않아서 제출횟수를 좀 날렸다.
class Solution {
public:
string convert(string s, int numRows) {
// ( numRows - 2 ) * 2
// 3 : 4, 2, 4
// 4 : 6, (4,2,4,2.. ), (2,4,2,4...), 6
// 5 : 8, (6,2,6,2...), (4,4,4,4..), (2,6,2,6...), 8
int std_gap = ( numRows - 2 ) * 2 + 2; // standard gap
int input_length = s.length();
string output;
for ( int i = 0; i < numRows; i++ )
{
if ( i == 0 || i == numRows - 1 )
{
//stdgap for the first and the end.
int index = i;
for ( index; index < input_length ; )
{
output += s[index];
if ( std_gap == 0 )
index++;
else
index += std_gap;
}
}
else
{
int index = i;
int count = 0;
// gap on zigzag
int gap1 = std_gap - i*2;
int gap2 = i*2;
for ( index; index < input_length ; )
{
int gap = gap1;
if ( count % 2 == 1)
gap = gap2;
output += s[index];
index += gap;
count ++;
}
}
}
return output;
}
};
'Algorithm things' 카테고리의 다른 글
[LeetCode] Weekly Contest 234 (0) | 2021.03.27 |
---|---|
[LeetCode] 62. Unique Paths (0) | 2021.03.27 |
[LeetCode] 5. Longest Palindromic Substring (0) | 2021.03.25 |
[LeetCode] Add Two Numbers (0) | 2021.03.21 |
[LeetCode] Two sum (0) | 2021.03.21 |