Introduction
In this article, we will solve the leetcode problem #1324, Print Words Vertically. The problem statement goes like this:
Given a string s return all the words vertically in the same order in which they appear in s. Words are returned as a list of strings, complete with spaces when is necessary. (Trailing spaces are not allowed). Each word would be put on only one column and that in one column there will be only one word.
static void Main(string[] args)
{
var result = printVertically("CONTEST IS COMING");
//result is ["CIC","OSO","N M","T I","E N","S G","T"]
result = printVertically("HOW ARE YOU");
//result is ["HAY","ORO","WEU"]
result = printVertically("TO BE OR NOT TO BE");
//result is ["TBONTB","OEROOE"," T"]
}
Solution
The algorithm is straight but more effective than using a tree data structure. The steps for solving the problem are as follows:
- Count the number of words in the given string, which will be the length of each element in the resulting array.
- Find the max number of letters among the words in the given string, which will be the number of elements in the resulting array.
- Now after getting the dimensions of the resulting array, we just have to traverse over the given string and store it in the resulting array.
However, don't forget to remove trailing spaces. Here is the C# code for the approach,
static List<string> printVertically(string s)
{
string[] words = s.Split(' ');
int columnMax = 0;
foreach (string word in words)
{
columnMax = Math.Max(columnMax, word.Length);
}
char[,] matrix = new char[words.Length, columnMax];
for (int i = 0; i < words.Length; i++)
{
int j = 0;
for (; j < words[i].Length; j++)
{
matrix[i, j] = words[i].ElementAt(j);
}
while (j < columnMax)
{
matrix[i, j++] = '#';
}
}
List<string> result = new List<string>();
for (int j = 0; j < columnMax; j++)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < matrix.GetLength(0); i++)
{
if (matrix[i, j] != '#')
{
sb.Append(matrix[i, j]);
}
else
{
sb.Append(' ');
}
}
string str = sb.ToString();
int k = str.Length - 1;
while (k >= 0 && str.ElementAt(k) == ' ')
{
k--;
}
result.Add(str.Substring(0, k + 1));
}
return result;
}