Input:
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
Output:
[
"This is an",
"example of text",
"justification. "
]
複製代碼
eg2:前端
Input:
words = ["What","must","be","acknowledgment","shall","be"]
maxWidth = 16
Output:
[
"What must be",
"acknowledgment ",
"shall be "
]
複製代碼
題目分析: 由於每一行最大字符數爲target,所以,每一一行中words[i]的字符長度總數之和必須小於target,且每一個words[i]之間須要至少一個空格。所以假設咱們第一行中有m項,各項字符總數爲count,那麼咱們count必須小於等於target - m + 1; 經過對words數組進行循環,計算出每一行的組成項,而後在每項之間使用相應適量的空格進行連接。可是有兩點須要特殊處理,1.某一行只有一項,這種狀況直接在該項後面加上相應數量的空格,2.最後一行,數組項之間採用單個空格連接,剩餘空格添加在最後。算法
具體算法以下:數組
const fullJustify = function(words, maxWidth) {
let str = []; //最終返回數組
let strArr = []; //每一行數組項數組
let diff = maxWidth; //當前行數剩餘字符數量
let total = 0; //每一行各項數組字符長度之和
for (let item of words) {
const len = item.length; //當前數組項字符長度
if (len <= diff) { //若是當前字符數量小於diff,則存入strArr,並更新diff
total += len;
strArr.push(item);
diff -= len + 1;
} else {
diff = maxWidth - total; //須要添加的空格數量
if (strArr.length <= 1) { //處理只有一項的特殊狀況
strArr[0] += ' '.repeat(diff);
} else {
while (diff > 0) { //爲每一行的數組前strArr.length - 1項添加空格
for (let i = 0; i < strArr.length; i++) {
if (diff > 0 && i < strArr.length - 1) {
strArr[i] = strArr[i] + ' ';
diff -= 1;
}
}
}
}
str.push(strArr.reduce((a, b) => a + b));
strArr = [item];
total = len;
diff = maxWidth - len - 1;
}
}
// 處理最後一行
diff = maxWidth - total - strArr.length + 1;
str.push(strArr.join(' ') + ' '.repeat(diff));
return str;
};
複製代碼
解題思路大體如上,固然還有不少更好的寫法,總體來講上述算法在運行耗時上表現不夠優秀,能夠考慮以空間換時間,再次我也只是拋磚引玉!bash