C# solution


  • 1
    R

    The magic happens in the StringIndexToRowIndex method. Use one StringBuilder per row, and iterate over each char in the string, using the StringIndexToRowIndex method to convert the string index to a row index, and put the char in the StringBuilder for that row.

         public class Solution
         {
            public string Convert(string s, int numRows)
            {
               if (numRows == 1 || s.Length < 2)
               {
                  return s;
               }
    
               StringBuilder[] builders = new StringBuilder[numRows];
    
               for (int i = 0; i < builders.Length; ++i)
               {
                  builders[i] = new StringBuilder();
               }
    
               for (int i = 0; i < s.Length; ++i)
               {
                  int rowIndex = StringIndexToRowIndex(i, numRows);
                  builders[rowIndex].Append(s[i]);
               }
    
               StringBuilder combine = new StringBuilder();
    
               for (int i = 0; i < builders.Length; ++i)
               {
                  combine.Append(builders[i].ToString());
               }
    
               return combine.ToString();
            }
    
            private int StringIndexToRowIndex(int stringIndex, int numRows)
            {
               int sectionLength = numRows * 2 - 2;
    
               if (stringIndex % sectionLength < numRows)
               {
                  return stringIndex % sectionLength;
               }
               else
               {
                  return sectionLength - (stringIndex % sectionLength);
               }
            }
         }

Log in to reply
 

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