Solution for ZigZag (C#)


  • 0
    L

    A example of s = "abcdefghijklmno" and numRows = 5

    0    a                i
    1    b            h     j
    2    c        g            k               o
    3    d    f                     l       n
    4    e                              m
    

    So this is an array whose length is 5
    We need a pointer and a direction to calculate the location

    public string Convert(string s, int numRows) {
            if(numRows < 2)
            {
                return s;
            }
            
            string[] result = new string [numRows];
            int row = 0;
            int direct = 1;
            
            for(int i = 0; i < s.Length; i++)
            {
                if(row == 0)
                {
                    direct = 1;
                }
                
                if(row == numRows - 1)
                {
                    direct = -1;
                }
                
                result[row] += s[i];
                row += direct;
            }
            
            string convert = "";
            for(int i = 0 ; i < result.Length; i ++)
            {
                convert += result[i];
            }
            
            return convert;
        }
    

Log in to reply
 

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