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 exactly L 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
http://buttercola.blogspot.com/2015/10/leetcode-text-justification.html
public static List<String> leftJustifiedText(List<String> words, int L) {
int lastIdx = 0, numWords = 0, len = 0;
List<String> res = new ArrayList<String>();
for (int i = 0; i < words.size(); ++i) {
++numWords;
int lineLen = len + words.get(i).length()
+ (numWords >= 2 ? numWords - 1 : 0);
if (lineLen == L) {
res.add(joinALineWithSpace(words, lastIdx, i, i - lastIdx));
lastIdx = i + 1;
numWords = 0;
len = 0;
} else if (lineLen > L) {
res.add(joinALineWithSpace(words, lastIdx, i - 1, L - len));
lastIdx = i;
numWords = 1;
len = words.get(i).length();
} else { // lineLen < L.
len += words.get(i).length();
}
}
// Handles the last line.
if (numWords != 0) {
res.add(joinALineWithSpace(words, lastIdx, words.size() - 1, L - len));
}
return res;
}
// Joins strings in words[start : end].
private static String joinALineWithSpace(List<String> words, int start,
int end, int numSpaces) {
int numWords = end - start + 1;
StringBuilder line = new StringBuilder();
for (int i = start; i < end; ++i) {
line.append(words.get(i));
int numCurrSpace = (int) Math.ceil((double) numSpaces / numWords - 1);
for (int j = 0; j < numCurrSpace; j++) {
line.append(' ');
}
numSpaces -= numCurrSpace;
--numWords;
}
line.append(words.get(end));
for (int j = 0; j < numSpaces; j++) {
line.append(' ');
}
return line.toString();
}
Read full article from LeetCode - Text Justification | Darren's Blog
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as
[
"This is an",
"example of text",
"justification. "
]
- 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.
public ArrayList<String> fullJustify(String[] words, int L) {
ArrayList<String> result = new ArrayList<String>();
if (words == null || words.length == 0)
return result;
int begin = 0, end = 0; // words[begin...end-1] as a line
while (begin < words.length) {
// Determine end such that words[begin...end-1] fit in a line and
// words[begin...end] do not.
int currentLength = words[begin].length();
for (end = begin+1; end < words.length; end++) {
if (currentLength + words[end].length() + 1 <= L)
currentLength += words[end].length() + 1;
else
break;
}
// Construct a justified line with words[begin...end-1]
StringBuilder temp = new StringBuilder();
temp.append(words[begin]);
if (end == words.length || end == begin+1) { // Last line or a line with only one word
// Left justified
for (int i = begin+1; i < end; i++) {
temp.append(' ');
temp.append(words[i]);
}
for (int i = 0; i < L - currentLength; i++)
temp.append(' ');
} else { // Regular lines
// Fully justified
int spaceInBetween = end - begin - 1;
double spaces = L - currentLength + spaceInBetween;
for (int i = begin+1; i < end; i++) {
for (int j = 0; j < spaces/spaceInBetween; j++) {
temp.append(' ');
}
spaces -= Math.ceil(spaces/spaceInBetween);
spaceInBetween--;
temp.append(words[i]);
}
}
// Add the line to the resulting list, and slide the window to the next position
result.add(temp.toString());
begin = end;
}
return result;
}
https://discuss.leetcode.com/topic/9147/simple-java-solution public List<String> fullJustify(String[] words, int L) {
List<String> lines = new ArrayList<String>();
int index = 0;
while (index < words.length) {
int count = words[index].length();
int last = index + 1;
while (last < words.length) {
if (words[last].length() + count + 1 > L) break;
count += words[last].length() + 1;
last++;
}
StringBuilder builder = new StringBuilder();
int diff = last - index - 1;
// if last line or number of words in the line is 1, left-justified
if (last == words.length || diff == 0) {
for (int i = index; i < last; i++) {
builder.append(words[i] + " ");
}
builder.deleteCharAt(builder.length() - 1);
for (int i = builder.length(); i < L; i++) {
builder.append(" ");
}
} else {
// middle justified
int spaces = (L - count) / diff;
int r = (L - count) % diff;
for (int i = index; i < last; i++) {
builder.append(words[i]);
if (i < last - 1) {
for (int j = 0; j <= (spaces + ((i - index) < r ? 1 : 0)); j++) {
builder.append(" ");
}
}
}
}
lines.add(builder.toString());
index = last;
}
return lines;
}
http://yuanhsh.iteye.com/blog/2191422- public List<String> fullJustify(String[] words, int L) {
- List<String> res = new ArrayList<>();
- int n = words.length;
- char[] spaces = new char[L];
- Arrays.fill(spaces, ' ');
- for(int i=0; i<n; i++) {
- int len = words[i].length();
- int j = i;
- while(i<n-1 && len+1+words[i+1].length()<=L) {
- len += 1+words[++i].length();
- }
- StringBuilder sb = new StringBuilder(words[j]);
- if(j == i || i==n-1) {
- while(i==n-1 && j < i) {
- sb.append(" "+words[++j]);
- }
- sb.append(spaces, 0, L-sb.length());
- } else {
- int avg = (L-len)/(i-j);
- int rem = (L-len)%(i-j);
- while(j < i) {
- sb.append(spaces, 0, avg+1);
- if(rem-- > 0) sb.append(" ");
- sb.append(words[++j]);
- }
- }
- res.add(sb.toString());
- }
- return res;
- }
- public List<String> fullJustify(String[] words, int L) {
- List<String> list = new ArrayList<>();
- int n = words.length;
- char[] spaces = new char[L];
- Arrays.fill(spaces, ' ');
- for(int i=0; i<n; i++) {
- int j = i;
- int len = words[i].length();
- while(i<n-1 && len+1+words[i+1].length()<=L) {
- len += 1+words[++i].length();
- }
- //只有一个word或者是最后一行的时候,需要左对齐
- boolean left = (j==i || i==n-1);
- int avg = left ? 0 : (L-len) / (i-j); //平均空格个数-1
- int rem = left ? 0 : (L-len) % (i-j); //平均之后多出来的空格个数
- StringBuilder sb = new StringBuilder(words[j]);
- while(j < i) {
- sb.append(spaces, 0, avg+1);
- if(rem-- > 0) sb.append(' ');
- sb.append(words[++j]);
- }
- sb.append(spaces, 0, L-sb.length());
- list.add(sb.toString());
- }
- return list;
- }
http://buttercola.blogspot.com/2015/10/leetcode-text-justification.html
public
List<String> fullJustify(String[] words,
int
maxWidth) {
List<String> result =
new
ArrayList<>();
if
(words ==
null
|| words.length ==
0
|| maxWidth <
0
) {
return
result;
}
if
(maxWidth ==
0
) {
result.add(
""
);
return
result;
}
fullJustifyHelper(
0
, words, result, maxWidth);
return
result;
}
private
void
fullJustifyHelper(
int
start, String[] words,
List<String> result,
int
L) {
if
(start >= words.length) {
return
;
}
int
total =
0
;
int
len =
0
;
int
next = -
1
;
int
i = start;
while
(i < words.length && total < L) {
total += words[i].length();
if
(total > L) {
next = i;
break
;
}
len += words[i].length();
total++;
i++;
}
if
(next == -
1
) {
next = i;
}
addLists(words, start, next, result, len, L);
fullJustifyHelper(next, words, result, L);
}
private
void
addLists(String[] words,
int
start,
int
next,
List<String> result,
int
len,
int
L) {
int
slots = next - start -
1
;
StringBuffer sb =
new
StringBuffer();
// Last line or only one word in a line
if
(slots ==
0
|| next == words.length) {
for
(
int
i = start; i < next; i++) {
sb.append(words[i]);
if
(i == next -
1
) {
break
;
}
sb.append(
" "
);
}
int
trailingSpace = L - len - slots;
for
(
int
i =
0
; i < trailingSpace; i++) {
sb.append(
" "
);
}
result.add(sb.toString());
}
else
{
int
aveSpace = (L - len) / slots;
int
moreSpace = (L - len) % slots;
for
(
int
i = start; i < next; i++) {
sb.append(words[i]);
if
(i == next -
1
) {
break
;
}
for
(
int
j =
0
; j < aveSpace; j++) {
sb.append(
" "
);
}
if
(moreSpace >
0
) {
sb.append(
" "
);
moreSpace--;
}
}
result.add(sb.toString());
}
}
vector<string> fullJustify(vector<string> &words, int L) { int start = 0, end = -1, totLen = 0; bool isLast = false; vector<string> ret; int i=0; while(i<words.size()) { if(words[i].size()>L) return ret; int newLen = totLen + (end-start+1) + words[i].size(); if(newLen<=L) { // words[i] can be in current line end = i; totLen += words[i].size(); i++; } else { // word[i-1] is the end of a line string line = createLine(words, L, start, end, totLen, false); ret.push_back(line); start = i; end = i-1; totLen = 0; } } string lastLine = createLine(words, L, start, end, totLen, true); ret.push_back(lastLine); return ret; } http://bangbingsyb.blogspot.com/2014/11/leetcode-text-justification.html
比较麻烦的字符串细节实现题。需要解决以下几个问题:1. 首先要能判断多少个word组成一行:这里统计读入的所有words的总长curLen,并需要计算空格的长度。假如已经读入words[0:i]。当curLen + i <=L 且加curLen + 1 + word[i+1].size() > L时,一行结束。2. 知道一行的所有n个words,以及总长curLen之后要决定空格分配:平均空格数:k = (L - curLen) / (n-1)前m组每组有空格数k+1:m = (L - curLen) % (n-1)例子:L = 21,curLen = 14,n = 4k = (21 - 14) / (4-1) = 2m = (21 - 14) % (4-1) = 1A---B--C--D3. 特殊情况:(a) 最后一行:当读入到第i = words.size()-1 个word时为最后一行。该行k = 1,m = 0(b) 一行只有一个word:此时n-1 = 0,计算(L - curLen)/(n-1)会出错。该行k = L-curLen, m = 0(c) 当word[i].size() == L时。
string createLine(vector<string> &words, int L, int start, int end, int totLen, bool isLast) { string ret; if(start<0 || end>=words.size() || start>end) return ret; ret.append(words[start]); int n = end-start+1; // special case: one word or last line - left justified if(n==1 || isLast) { for(int i=start+1; i<=end; i++) ret.append(" " + words[i]); int j = L-totLen-(n-1); ret.append(j, ' '); return ret; } // normal case: fully justified int k = (L-totLen)/(n-1), m = (L-totLen)%(n-1); for(int i=start+1; i<=end; i++) { int nspace = i-start<=m ? k+1 : k; ret.append(nspace,' '); ret.append(words[i]); } return ret; }https://github.com/writecoffee/algorithms/blob/master/algo4/greedy/gd_text_justification.java
public ArrayList<String> fullJustify(String[] words, int L) {
ArrayList<String> result = new ArrayList<String>();
int i = 0, m = words.length;
while (i < m) {
int n = words[i].length(), next = i + 1;
while (next < m && n + words[next].length() + (next - i) <= L) {
n += words[next++].length();
}
StringBuilder sb = new StringBuilder();
sb.append(words[i]);
boolean isLastLine = (next == m);
boolean oneWord = (next == i + 1);
int average = isLastLine || oneWord ? 1 : (L - n) / (next - i - 1);
int extra = isLastLine || oneWord ? 0 : (L - n) % (next - i - 1);
for (int j = i + 1; j < next; ++j, --extra) {
sb.append(fillChar(extra > 0 ? average + 1 : average, ' '));
sb.append(words[j]);
}
result.add(sb.append(fillChar(L - sb.length(), ' ')).toString());
i = next;
}
return result;
}
private String fillChar(int count, char c) {
char[] array = new char[count];
Arrays.fill(array, c);
return new String(array);
}
Left Justify Text from EPIpublic static List<String> leftJustifiedText(List<String> words, int L) {
int lastIdx = 0, numWords = 0, len = 0;
List<String> res = new ArrayList<String>();
for (int i = 0; i < words.size(); ++i) {
++numWords;
int lineLen = len + words.get(i).length()
+ (numWords >= 2 ? numWords - 1 : 0);
if (lineLen == L) {
res.add(joinALineWithSpace(words, lastIdx, i, i - lastIdx));
lastIdx = i + 1;
numWords = 0;
len = 0;
} else if (lineLen > L) {
res.add(joinALineWithSpace(words, lastIdx, i - 1, L - len));
lastIdx = i;
numWords = 1;
len = words.get(i).length();
} else { // lineLen < L.
len += words.get(i).length();
}
}
// Handles the last line.
if (numWords != 0) {
res.add(joinALineWithSpace(words, lastIdx, words.size() - 1, L - len));
}
return res;
}
// Joins strings in words[start : end].
private static String joinALineWithSpace(List<String> words, int start,
int end, int numSpaces) {
int numWords = end - start + 1;
StringBuilder line = new StringBuilder();
for (int i = start; i < end; ++i) {
line.append(words.get(i));
int numCurrSpace = (int) Math.ceil((double) numSpaces / numWords - 1);
for (int j = 0; j < numCurrSpace; j++) {
line.append(' ');
}
numSpaces -= numCurrSpace;
--numWords;
}
line.append(words.get(end));
for (int j = 0; j < numSpaces; j++) {
line.append(' ');
}
return line.toString();
}
Read full article from LeetCode - Text Justification | Darren's Blog