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;
1 class Solution { 2 public: 3 vector<string> fullJustify(vector<string> &words, int L) { 4 5 int n=words.size(); 6 7 vector<string> result; 8 9 int count=0; 10 int totalWordsLen=0; 11 int startIndex=0; 12 13 string tmpStr; 14 15 for(int i=0;i<n-1;i++) 16 { 17 count++; 18 totalWordsLen+=words[i].size(); 19 int len=totalWordsLen+count-1; 20 21 if(len+words[i+1].size()+1>L) 22 { 23 tmpStr=formLine(startIndex,i,L,totalWordsLen,words); 24 result.push_back(tmpStr); 25 26 count=0; 27 totalWordsLen=0; 28 startIndex=i+1; 29 } 30 } 31 32 tmpStr=formLastLine(startIndex,L,words); 33 result.push_back(tmpStr); 34 35 return result; 36 } 37 string formLine(int start,int end,int &L,int totalWordsLen,vector<string> &words) 38 { 39 int n=end-start; 40 int spaceNum=L-totalWordsLen; 41 if(n==0) return words[start]+string(spaceNum,‘ ‘); 42 43 int n1=spaceNum/n; 44 int n2=spaceNum%n; 45 46 vector<int> space(n,n1); 47 for(int i=0;i<n2;i++) space[i]+=1; 48 49 string tmpStr=""; 50 for(int i=start;i<end;i++) 51 { 52 tmpStr+=(words[i]+string(space[i-start],‘ ‘)); 53 } 54 55 tmpStr+=words[end]; 56 return tmpStr; 57 58 } 59 60 string formLastLine(int start,int &L,vector<string> &words) 61 { 62 string tmpStr=words[start]; 63 for(int i=start+1;i<words.size();i++) 64 { 65 tmpStr+=‘ ‘+words[i]; 66 } 67 while(tmpStr.length()<L) 68 { 69 tmpStr+=‘ ‘; 70 } 71 return tmpStr; 72 } 73 }; 74