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."]
L16.

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.

class Solution {
public:
    void justify(string &result,int L,bool last){
        int n=result.size();
        if(n==0) //空串调整
            for(int i=0;i<L;i++)
                result+=' ';
        else if(n<L){
            int diff=L-n;
            while(diff>0&&!last)
                for(int i=0;i<result.size()&&diff>0;i++){
                    if(result[i]==' '&&result[i+1]!=' '){ //普通调整
                        result.insert(++i,1,' ');
                        diff--;
                    }
                    if(i==result.size()-1&&diff==L-n) //只有一个单词的调整
                        while(diff-->0) result+=' ';
                }
            if(last) //最后一行的调整
                for(int i=n;i<L;i++)
                    result+=' ';
        }
    }
    vector<string> fullJustify(vector<string> &words, int L) {
        vector<string> result;
        string temp;
        for(int i=0;i<words.size();i++){
            if((temp.size()!=0&&temp.size()+words[i].size()+1<=L)||(temp.size()==0&&words[i].size()<=L)){
                if(temp.size()!=0) temp.push_back(' ');
                temp+=words[i];
            } 
            else{
                justify(temp,L,false);
                result.push_back(temp);
                temp.clear();
                temp=words[i];
            }
        }
        justify(temp,L,true);
        result.push_back(temp);
        return result;
    }
};


你可能感兴趣的:(LeetCode,算法)