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);
Constraints: 1 <= s.length <= 1000s consists of English letters (lower-case and upper-case), ',' and '.'.1 <= numRows <= 1000
코드 원문
class Solution {
public:
string convert(string s, int numRows) {
}
};
풀이
문제의 설명은 지그제그로 배치되는 것을 보여주기 위해 각 행의 숫자를 띄워 놨지만
실제 풀이할 때는 띄울 필요가 없고 문자도 순서대로 들어오기 때문에 문자의 위치와 행의 갯수를 매개변수로 받아 행 위치를 리턴하는 함수를 작성하여 풀이하였습니다.
다만 행의 갯수가 1일 경우 원점 값이 0이 되기 때문에 예외처리해주었습니다.
입력값을 순회하여 각 행 문자열에 추가하고 마지막으로 각 행의 문자열을 순서대로 합하여 반환하였습니다.
성공 코드
class Solution {
public:
int ZigZagRow(int pos, int numRows)
{
int ZeroPosition = numRows + numRows - 2; //원점 계산
if (ZeroPosition == 0) return 0; //0이면 나눌수 없기 때문에 예외처리
int Remaninder = pos % ZeroPosition;//나머지 값 계산
if (Remaninder < numRows) //나머지 값이 numRows보다 작으면 순서대로기 때문에 나머지 값 반환
{
return Remaninder;
}
else //나머지 값이 numRows보다 크거나 같으면 역순이기 때문에 계산하여 반환
{
return ZeroPosition - Remaninder;
}
}
string convert(string s, int numRows) {
string answer = "";
vector<string> Zigzag(numRows, "");
for (int i = 0; i < s.size(); i++)
{
Zigzag[ZigZagRow(i, numRows)] += s[i]; //주어진 문자열을 순서대로 Row를 계산하여 저장
}
for (int i = 0; i < Zigzag.size(); i++)
{
answer += Zigzag[i]; //저장한 Row별 문자열을 재조합
}
return answer;
}
};