[LeetCode][JavaScript]Text Justification
Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' '
when necessary so that each line has exactlyL characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16
.
Return the formatted lines as:
[ "This is an", "example of text", "justification. " ]
Note: Each word is guaranteed not to exceed L in length.
- A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
https://leetcode.com/problems/text-justification/
fullJustify([""], 2);这个Case怎么回事,fullJustify([""], 0);这也就算了,可以接受。
你明明输入空字符串,还要我给你格式化成2个空格,返回空算错,不讲道理,如果输入两个空呢,你叫我怎么格式化:fullJustify(["", ""], 2);
要我说全算是异常情况,return [];
第一轮遍历的时候用#把字符串分割出来,比如例子中的第一行就是This#is#an。
这样操作起来就很方便,如果是最后一行,直接把#替换成空格,最后补足长度。
如果非最后行,计算需要多少空格的时候就把#替换成空,用maxWidth减去length就好了。
1 /** 2 * @param {string[]} words 3 * @param {number} maxWidth 4 * @return {string[]} 5 */ 6 var fullJustify = function(words, maxWidth) { 7 var result = []; 8 if(words[0] === ""){ 9 return [nBlanks(maxWidth)]; 10 } 11 var row = ""; 12 var curr = ""; 13 for(var i = 0; i < words.length; i++){ 14 if(row === ""){ 15 curr = words[i]; 16 }else{ 17 curr = "#" + words[i]; 18 } 19 if(row.length + curr.length <= maxWidth){ 20 row += curr; 21 }else{ 22 result.push(format(row)); 23 row = words[i]; 24 } 25 } 26 if(row !== ""){ 27 var lastRow = row.replace(/#/g, " "); 28 result.push(lastRow + nBlanks(maxWidth - lastRow.length)); 29 } 30 return result; 31 32 function format(str){ 33 var res = ""; 34 var splited = str.split('#'); 35 if(splited.length === 1){ 36 res = splited + nBlanks(maxWidth - splited[0].length); 37 }else{ 38 var charsLen = str.replace(/#/g, "").length; 39 var needBlanks = maxWidth - charsLen; 40 var wordBlanks = parseInt(needBlanks / (splited.length - 1)); 41 var remainBlanks = needBlanks - wordBlanks * (splited.length - 1); 42 res = splited[0]; 43 for(var i = 1; i < splited.length; i++, remainBlanks--){ 44 if(remainBlanks > 0 ){ 45 res += " " + nBlanks(wordBlanks); 46 }else{ 47 res += nBlanks(wordBlanks); 48 } 49 res += splited[i]; 50 } 51 } 52 return res; 53 } 54 function nBlanks(n){ 55 var res = ""; 56 for(var i = 0; i < n; i++){ 57 res += " "; 58 } 59 return res; 60 } 61 };