C# Solution O(n) runtime O(n) space (Beats 98%)


  • 0
    K
    public class Solution {
        public string Convert(string s, int numRows)
        {
            if (String.IsNullOrEmpty(s) || numRows == 1)
                return s;
        
            var dict = new Dictionary<int, StringBuilder>();
            int start = 0;
            bool down = true;
            for(int i = 0; i < numRows; ++i){
                dict[i] = new StringBuilder();
            }
            for(int i = 0; i < s.Length; ++i){
                dict[start].Append(s[i]);
                if (start == numRows - 1){
                    down = false;
                }
                else if (start == 0){
                    down = true;
                }
                
                if (down){
                    start++;
                }
                else{
                    start--;
                }
            }
            
            StringBuilder sb = dict[0];
            for(int i = 1; i < numRows; ++i){
                sb.Append(dict[i]);
            }
            return sb.ToString();
            
        }
    }

Log in to reply
 

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