public class Solution {
public IList<string> FullJustify(string[] words, int maxWidth) {
// all items scope
List<List<string>> linesWords = new List<List<string>>();
List<int[]> paddingOfLineInfo = new List<int[]>();
// in item scope
List<string> currentLineWords = new List<string>();
int currentLineWordCount = 0, currentLineLength = 0, newLineLength, padLength, padEachWordSpaceLength, remainSpaceLength, i, j, lineLength, wordLength = words.Length;
for(i = 0; i < wordLength; i++) {
newLineLength = currentLineLength + words[i].Length + (currentLineLength > 0 ? 1 : 0) /* space */;
if(newLineLength > maxWidth) { // start padding
// get padding info
padLength = maxWidth - currentLineLength;
if(currentLineWordCount > 1) {
padEachWordSpaceLength = padLength / (currentLineWordCount - 1);
remainSpaceLength = padLength % (currentLineWordCount - 1);
} else {
padEachWordSpaceLength = padLength;
remainSpaceLength = 0;
}
// break line
paddingOfLineInfo.Add(new int[]{padEachWordSpaceLength, remainSpaceLength});
linesWords.Add(currentLineWords);
currentLineWords = new List<string>();
currentLineLength = 0;
currentLineWordCount = 0;
// add current word to the first place of the new line
currentLineWords.Add(words[i]);
currentLineWordCount = 1;
currentLineLength = words[i].Length;
} else {
currentLineWords.Add(words[i]);
currentLineWordCount++;
currentLineLength += words[i].Length + (currentLineLength > 0 ? 1 : 0) /* space */;
}
if(i >= words.Length - 1) { // the last word
// complete line
linesWords.Add(currentLineWords);
}
}
// return new List<string>();
// print result
lineLength = linesWords.Count;
List<string> result = new List<string>();
string currentLine, padStart;
int padStartLength;
for(i = 0; i < lineLength; i++) {
currentLineWordCount = linesWords[i].Count;
currentLine = "";
for(j = 0; j < currentLineWordCount; j++) {
padStartLength = 0; // pad start
if(j > 0) { // not the first word in line
padStartLength++; // space
if(i < lineLength - 1) { // current line is not the last line
// add padding
padStartLength += paddingOfLineInfo[i][0] + (paddingOfLineInfo[i][1] > 0 ? 1 : 0);
if(paddingOfLineInfo[i][1] > 0) paddingOfLineInfo[i][1]--;
}
}
padStart = new string(' ', padStartLength);
currentLine += padStart + linesWords[i][j];
if(j >= currentLineWordCount - 1 && maxWidth - currentLine.Length > 0)
currentLine += new string(' ', maxWidth - currentLine.Length);
}
result.Add(currentLine);
}
return result;
}
}