C# solution: reading chars one by one based on the rule


  • 0
    B
    public class Solution 
    {
        public enum Direction { Up, Down }
        public string Convert(string s, int numRows) 
        {
            if (numRows == 1) return s;
            
            var n = s.Length;
    
            var rowList = new List<StringBuilder>();
            for (int i = 0; i < numRows; i++)
            {
                rowList.Add(new StringBuilder());
            }
    
            var direction = Direction.Down;
            var curRow = 0;
    
            for (int i = 0; i < s.Length; i++)
            {
                rowList[curRow].Append(s[i]);
    
                if (direction == Direction.Down)
                {
                    curRow++;
                }
                else if (direction == Direction.Up)
                {
                    curRow--;
                }
    
                if (curRow == numRows)
                {
                    curRow -= 2;
                    direction = Direction.Up;
                }
                else if (curRow == -1)
                {
                    direction = Direction.Down;
                    curRow = 1;
                }
            }
    
            var result = new StringBuilder();
    
            foreach(var row in rowList)
            {
                result.Append(row.ToString());
            }
    
            return result.ToString();
        }
    }
    

Log in to reply
 

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