
이번 문제는 푸는데 오래걸렸습니다! 답을 참고할까 생각도 해봤지만, 조금만 더하면 풀 수 있을 것 같아 계속 도전했고, 그리고 찢었습니다 ㅎ 알린이는 이런거로도 행복해요~
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)

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);
s.length <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.주어진 문자열을 지그재그 방식으로 위치를 바꿀 경우의 문자열 값을 반환하는 문제였어요.
여러가지를 시도해봤던 문제였습니다. 결국 패턴을 찾는 것이 문제였어요. 그리고 제가 발견한 패턴은 아래와 같아요. s를 예제 그대로 주고, numRows를 5로 주게 되면,
| Row | P | A | Y | P | A | L | I | S | H | I | R | I | N | G |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 0 | 1 | ||||||||||||
| 1 | 2 | 3 | 4 | |||||||||||
| 2 | 5 | 6 | 7 | |||||||||||
| 3 | 8 | 9 | 10 | 11 | ||||||||||
| 4 | 12 | 13 |
보시면 파장 모양으로 되어 있습니다. 처음 간격은 보시면 8입니다. 지그재그 모양을 보면 일직선으로 내려가는 시점 간의 간격은 6, 즉 가 됩니다.
그리고 row가 내려갈 수록, 또는 를 번갈아 가며 인덱스를 주어 문제를 해결하면 됩니다. 물론 처음과 마지막은 간격이 일관되므로 따로 예외 처리해주시면 됩니다.
class Solution {
public String convert(String s, int numRows) {
if(numRows <= 1)
return s;
String answer = "";
for(int i = 0; i < numRows; ++i){
for(int j = i, cnt = 0; j < s.length(); ++cnt){
answer += s.charAt(j);
int offset = 2 * numRows - 2;
if(i != 0 && i != (numRows - 1)){
if(cnt % 2 == 0){
offset -= (2 * i);
}
else{
offset = 2 * i;
}
}
j += offset;
}
}
return answer;
}
}