Text Justification
来源:互联网 发布:rup软件过程模型 编辑:程序博客网 时间:2024/06/05 10:30
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.
click to show corner cases.
- 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 List<String> fullJustify(String[] words, int L) {
List<String> res = new ArrayList<>();
if(words==null||words.length==0||L<0)
return res;
int b=0,e=-1,w=0;
for(int i=0;i<words.length;i++)
{
if(w==0||w+e-b+words[i].length()+1<=L)
{
w += words[i].length();
e++;
}
else
{
StringBuilder str = new StringBuilder();
if(e==b)
{
str.append(words[b]);
int tmp = L - w;
while(tmp-->0)
str.append(" ");
}
else
{
str.append(words[b]);
int d = (L-w)/(e-b);
int r = (L-w)%(e-b);
for(int j=b+1;j<=e;j++)
{
int tmp = d + (r-->0?1:0);
while(tmp-->0)
str.append(" ");
str.append(words[j]);
}
}
w = words[i].length();
b = i;
e = i;
res.add(str.toString());
}
}
if(w>0||res.size()==0)
{
StringBuilder str = new StringBuilder();
str.append(words[b]);
for(int j=b+1;j<=e;j++)
{
str.append(" ");
str.append(words[j]);
}
int tmp = L - (w + e - b);
while(tmp-->0)
str.append(" ");
res.add(str.toString());
}
return res;
}
}
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- Text Justification
- C++的输入和输出与标准输出流
- JAVA socket编程实例(标注)
- 获得android手机屏幕的宽高的类
- gnuplot配置HOME目录
- hive-0.12安装详解
- Text Justification
- 如果你做的事情毫不费力,就是在浪费时间
- hive元数据配置本地mysql出错
- POJ-1003 Hangover
- 常用排序算法之直接选择排序java版
- Selenium IDE使用说明
- 关于for循环的一个小差别
- Hadoop+Hive+Mysql安装文档
- eclipse working set管理项目