Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

개발 일지

6. Zigzag Conversion (지그재그 변환) 본문

코딩 테스트/LeetCode

6. Zigzag Conversion (지그재그 변환)

포카리tea 2023. 5. 9. 00:25

문자열은 "PAYPALISHIRING"다음과 같이 지정된 행 수에 지그재그 패턴으로 작성됩니다. 

P   A   H   N
A P L S I I G
Y   I   R

그런 다음 한 줄씩 읽습니다."PAHNAPLSIIGYIR" 

문자열을 사용하여 여러 행에 대해 이 변환을 수행하는 코드를 작성하십시오.

string convert(string s, int numRows);

 

예시 1:

입력: s = "PAYPALISHIRING", numRows = 3
출력: "PAHNAPLSIIGYIR"

 

예시 2:

입력: s = "PAYPALISHIRING", numRows = 4
출력: "PINALSIGYAHRPI"
설명:
P     I    N
A   L S  I G
Y A   H R
P     I

 

예시 3:

입력: s = "A", numRows = 1
출력: "A"

 

조건:

  • 1 <= s.length <= 1000
  • s는 영문자(소문자 및 대문자), ', '.'로 구성됩니다.
  • 1 <= numRows <= 1000

 

정답:

public class Solution {
    public string Convert(string s, int numRows) {
        if (numRows == 1)
        {
            return s;
        }
        
        List<string> str = new List<string>();
        
        int index = numRows - 2;
        bool down = true;
        
        for (int i = 0; i < s.Length; i++)
        {
            if (i < numRows)
            {
                str.Add(s[i].ToString());
            }
            else
            {
                str[index] += s[i].ToString();
                
                if (index == 0)
                {
                    down = false;
                }
                else if (index == numRows - 1)
                {
                    down = true;
                }
                
                if (down)
                {
                    index -= 1;
                }
                else
                {
                    index += 1;
                }
            }
        }

        string result = "";
        for (int i = 0; i < str.Count; i++)
        {
            result += str[i];
        }
        
        return result;
    }
}

해설: 

배열 크기를 설정해주기 위해 첫번째는 add로 추가해주었고 그 이후부터 index를 이용하여 지그재그로 문자열을 추가할 수 있게하고 마지막에 모두 더해주었습니다.