Friday, September 11, 2020

Given a string and number of rows ‘n’. Print the string formed by concatenating n rows when input string is written in row-wise Zig-Zag fashion.

Approach:

  1. Create an array of n strings say result
  2. Initialize direction as "down" and row as 0. The direction indicates whether we need to move up or down in rows. 
  3. Traverse the input string, do following for every character.
    •    a) Append current character to string of current row.
    •    b) If row number is n-1, then change direction to 'up'
    •    c) If row number is 0, then change direction to 'down'
    •    d) If direction is 'down', do row++.  Else do row--.

    public enum Direction

    {

        Down = 0,

        Up

    }


    public class ConvertString

    {

          public string ZigZagConvert(string s, int numRows)

        {

            if (string.IsNullOrEmpty(s))

            {

                return string.Empty;

            }

            if (numRows <= 1)

            {

                return s;

            }

            string[] strings = new string[numRows];

            int currIndex = 0;

            Direction direction = Direction.Down;

            foreach(char ch in s)

            {

                if (strings[currIndex] == null)

                {

                    strings[currIndex] = string.Empty;

                }

                strings[currIndex] += ch;

                if (direction == Direction.Down)

                {

                    if (currIndex == numRows - 1)

                    {

                        --currIndex;

                        direction = Direction.Up;

                    }

                    else

                    {

                        ++currIndex;

                    }

                }

                else

                {

                    if (currIndex == 0)

                    {

                        ++currIndex;

                        direction = Direction.Down;

                    }

                    else

                    {

                        --currIndex;

                    }

                }

            }

            return string.Join("", strings);

        }

No comments:

Post a Comment