C# solution, easy to understand


  • 1
    G

    Let's take a look at an example first:

    0       6       12                                        
    1    5  7    11 13                                        
    2  4    8  10   14                                      
    3       9       15  
    

    From the above example, the common distance between two adjacent char in first line is dist = (numRows-1)2, we can see for the first line and last line the formula is 6n+0 and 6n+3, it can simplify to distcol+row. But for the middle horizontal lines, there are 2 formulas, diststep-row* and diststep+row*
    For example: line #2, it can be divided into two arrays [1 7 13] and [5 11], and the formula are 6n+1 and 6n -1.

    public class Solution{
        public string convert(string s, int numRows){
            StringBuilder sb = new StringBuilder(s.Length);
            int dist= (numRows-1)*2;
            dist= dist==0?1:dist; // if there is only one line.
            for(int i=0;i<numRows;i++)
            {
                for(int j=0;j<s.Length;j++)
                {
                    if(i>0 && i<numRows-1 && dist*j-i>0 && dist*j-i<s.Length)  sb.Append(s[dist*j-i]);
                    if(dist*j+i<s.Length)   sb.Append(s[dist*j+i]);
                    else break;
            }
        }
        
        return sb.ToString();
    }
    

    }


Log in to reply
 

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