The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R

And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

Required Knowledge:

  1. Basics of C# Programming language

Program:

public class Solution {
    public string Convert(string s, int numRows) {
        
        //Corner case when numRows is 1, we need to return same string
        if(numRows == 1)
            return s;
        
        /*Declare string array with numRows
          For ex: if numRows is 2. 
          str - []
                []
        */
        string[] str = new string[numRows];
        
        //To track the direction, we use down variable
        bool down = true;

        /*To identify which row we are, and to store the char values in s
        by using row */
        int row = 0;
        
        foreach(char c in s)
        {
            
            str[row] = str[row] + c;
            
            if(down)
            {
                row = row + 1;
            }
            else
            {
                row = row - 1;
            }
            if(row == 0 || row == (numRows-1))
             down = !down;
        }
        string result = "";
        foreach(string s1 in str) 
            result += s1;
        
        return result;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s