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: [ "This is an", "example of text", "justification. " ] Note: Each word is guaranteed not to exceed L in length. click to show corner cases. 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.
思路:又是字符串處理,太煩人了。關鍵要注意的就是對最後一行的處理,用一個空格分割單詞,剩餘部分用空格填充。對每一行,儘可能放多單詞,用盡量相同空格的分割單詞。app
首先,計算每行單詞間有多少空格,和剩餘多少空格,這經過該行應該放多少單詞和長度決定的;ide
而後,處理最後一行字符串函數,單詞間儘可能用一個空格和剩餘部分用空格填充,這個不難。函數
最後,就是具體處理了。this
class Solution { public: string addHandle(vector<string> &word,int L,int wordL) { string result; int nLen=word.size(); if(nLen==1) { result+=word[0]; for(int i=0;i<L-wordL;i++) result+=" "; return result; } int d=(L-wordL)/(nLen-1); int r=(L-wordL)%(nLen-1); result+=word[0]; for(int i=1;i<nLen;i++) { for(int j=0;j<d;j++) result+=" "; if(r>0) { result+=" "; r--; } result+=word[i]; } return result; } string strEnd(vector<string> &word,int L,int count) { string result; result+=word[0]; for(int i=1;i<word.size();i++) { result+=" "+word[i]; } for(int i=0;i<L-count;i++) result+=" "; return result; } vector<string> fullJustify(vector<string> &words, int L) { vector<string> result; vector<string> word; int count=-1,wordL=0; for(int i=0;i<words.size();i++) { if(count+words[i].size()+1>L) { result.push_back(addHandle(word,L,wordL)); word.clear(); count=-1; wordL=0; } count+=1+words[i].size(); wordL+=words[i].size(); word.push_back(words[i]); } result.push_back(strEnd(word,L,count)); return result; } };