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 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.

思路:又是字符串处理,太烦人了。关键要注意的就是对最后一行的处理,用一个空格分割单词,剩余部分用空格填充。对每一行,尽量放多单词,用尽可能相同空格的分割单词。

首先,计算每行单词间有多少空格,和剩余多少空格,这通过该行应该放多少单词和长度决定的;

然后,处理最后一行字符串函数,单词间尽量用一个空格和剩余部分用空格填充,这个不难。

最后,就是具体处理了。

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;
    }
};

 

posted @ 2014-07-06 17:29  Awy  阅读(222)  评论(0编辑  收藏  举报