My simple C# solution


  • 0
    W

    My simple C# solution. To understand the problem, we can simply use the indexes to draw the zigzag instead of the characters. By doing this, we should be able to see the pattern more clearly:

    public class Solution {
        public string Convert(string s, int numRows) {
            if(numRows == 1)
                return s;
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < numRows; i ++)
            {
                bool b = true;
                int j = i;
                int jj = -1;
                while(j < s.Length)
                {
                    if(jj != j)
                    {
                        jj = j;
                        sb.Append(s[j]);
                    }
                    
                    if(b)
                        j = j + (numRows - i - 1 ) * 2 ;
                    else
                        j = j + (i * 2);
                    
                    b = !b;
                }
            }
            
            return sb.ToString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.