-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
62 lines (58 loc) · 1.98 KB
/
Solution.cs
File metadata and controls
62 lines (58 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#if DEBUG
using System.Text;
#endif
public class Solution
{
public IList<string> FullJustify(string[] words, int maxWidth)
{
List<string> result = [];
for (int i = 0; i < words.Length; i++)
{
int width = words[i].Length;
int st = i;
while (st + 1 < words.Length && (width + words[st + 1].Length) < maxWidth - (st - i))
{
st++;
width += words[st].Length;
}
if (st == words.Length - 1)
{
string spaces = string.Join("", Enumerable.Repeat(' ', maxWidth - width - (st - i)));
result.Add(string.Join(" ", words[i..(st + 1)]) + spaces);
}
else if (st == i)
{
string spaces = string.Join("", Enumerable.Repeat(' ', maxWidth - width));
result.Add(words[i] + spaces);
}
else
{
if ((maxWidth - width) % (st - i) == 0)
{
string spaces = string.Join("", Enumerable.Repeat(' ', (maxWidth - width) / (st - i)));
result.Add(string.Join(spaces, words[i..(st + 1)]));
}
else
{
string spaces = string.Join("", Enumerable.Repeat(' ', (maxWidth - width) / (st - i)));
StringBuilder sb = new();
int k = 0;
for (; k < (maxWidth - width) % (st - i); k++)
{
sb.Append(words[k + i]);
sb.Append(spaces + " ");
}
for (; k < (st - i); k++)
{
sb.Append(words[k + i]);
sb.Append(spaces);
}
sb.Append(words[k + i]);
result.Add(sb.ToString());
}
}
i = st;
}
return result;
}
}