【leetcode】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.

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.
 
 

1.每两个单词之间至少一个空格

2.相邻空格数目之差不超过1
3.在左边的空格数目一定不小于右边空格的数目
4.如果一行只有一个单词,则左对齐,后面插空格
5.对于最后一行,左对齐,两个单词之间必须只空一个空格
 
对于非最后一行,假设所有单词的总长度为totalWordsLen,则必须插入的空格书为spaceNum=L-totalWordsLen
设共有n+1个单词,则有n个间隔
 
则第i个间隔处的空格数space[i]可以通过下面计算
int n1=spaceNum/n;
int n2=spaceNum%n;
vector<int> space(n,n1);
for(int i=0;i<n2;i++)  space[i]+=1;
 
 class Solution {
public:
vector<string> fullJustify(vector<string> &words, int L) { int n=words.size(); vector<string> result; int count=;
int totalWordsLen=;
int startIndex=; string tmpStr; for(int i=;i<n-;i++)
{
count++;
totalWordsLen+=words[i].size();
int len=totalWordsLen+count-; if(len+words[i+].size()+>L)
{
tmpStr=formLine(startIndex,i,L,totalWordsLen,words);
result.push_back(tmpStr); count=;
totalWordsLen=;
startIndex=i+;
}
} tmpStr=formLastLine(startIndex,L,words);
result.push_back(tmpStr); return result;
}
string formLine(int start,int end,int &L,int totalWordsLen,vector<string> &words)
{
int n=end-start;
int spaceNum=L-totalWordsLen;
if(n==) return words[start]+string(spaceNum,' '); int n1=spaceNum/n;
int n2=spaceNum%n; vector<int> space(n,n1);
for(int i=;i<n2;i++) space[i]+=; string tmpStr="";
for(int i=start;i<end;i++)
{
tmpStr+=(words[i]+string(space[i-start],' '));
} tmpStr+=words[end];
return tmpStr; } string formLastLine(int start,int &L,vector<string> &words)
{
string tmpStr=words[start];
for(int i=start+;i<words.size();i++)
{
tmpStr+=' '+words[i];
}
while(tmpStr.length()<L)
{
tmpStr+=' ';
}
return tmpStr;
}
};
 
 
上一篇:Python - SIP参考指南 - 介绍


下一篇:Linux下查看IP的命令:ifconfig -a