본문 바로가기

Programing/Algorithm

[LeetCode] 6. Zigzag Conversion

728x90

 

 

 

https://leetcode.com/problems/zigzag-conversion/description/

 

public class Solution
{
    public string Convert(string s, int numRows)
    {
        if (numRows == 1)
            return s;

        var sbs = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++)
        {
            sbs[i] = new StringBuilder();
        }

        int index = 0;
        bool reverse = false;

        for (int i = 0; i < s.Length; i++)
        {
            sbs[index].Append(s[i]);

            if (index == 0)
                reverse = false;

            if (index == (numRows - 1))
                reverse = true;

            index = reverse ? (index - 1) : (index + 1);
        }

        var answer = string.Empty;
        foreach (var sb in sbs)
        {
            answer += sb.ToString();
        }

        return answer;
    }
}

 

 

 

728x90