sourcecode

Wednesday, January 2, 2013

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 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.
class Solution {
public:
    vector<string> fullJustify(vector<string> &words, int L) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!L || words.empty()) return words;
        vector<string> r;
        int wcount = 0;
        int cat_length = 0;
        int start = 0;//word index 
        for(int ii = 0; ii < words.size(); ++ii){//word index
            if (cat_length + wcount + words[ii].length() > L){
                string line(words[start]);
                if (wcount < 2){
                    line += string(L-cat_length,' ');
                }else{
                    string space((L-cat_length)/(wcount-1),' ');
                    int extra_index = (L-cat_length)%(wcount-1);
                    for(int jj = start+1; jj < ii; ++jj){
                        if (jj - start <= extra_index) line += ' ';
                        line += space;
                        line += words[jj];
                    }
                }//if else (wcount < 2)
                r.push_back(line);
                start = ii;
                cat_length = words[start].length();
                wcount = 1;
            }else{
                cat_length += words[ii].length();
                ++wcount;
            }
            
        }//for ii
        
        string line(words[start]);
        for(int ii = start+1; ii < words.size(); ++ii){
            line += ' ';
            line += words[ii];
        }
        line += string(L-line.length(),' ');
        r.push_back(line);

        return r;
    }
};

No comments: