Simple, Easy to Understand C++ Solution with Comments

  • 0
    vector<string> fullJustify(vector<string>& words, int l) {
            vector<string> ans;
            string row;
            int word_cnt=0, c_cnt=0; //word and char count per row
            for(auto w: words){ 
                //if last word doesn't fit in row,call format to space all words in row, 
                //save row, reset row and start a new row
                if (row.size()+w.size()>l){ 
                    int sp_areas=word_cnt-1;    //last word doesn't have space at end
                    string s=format(row,l,sp_areas, c_cnt); //
                    word_cnt=0, c_cnt=0;
                row+=w+' ';       //add word to row
                c_cnt+=w.size();  //record char cnt
                word_cnt++;       //increment word count
            if(row!=""){ //space last word
                row.resize(l,' ');
            return ans;
        string format(string str, int l, int sp_areas,int c_cnt){//this will space out each word
            //sp_areas: # space areas, each_space_size: size of each space area
            //leftover: leftover space 
            //Ex: "example  of text" has 2 space areas which are between the words
           //if l=17, sp_areas=2, total_spaces=17-10=7, each_space_size=7/2=3, leftover=7-(2*3)=1
            //Output: example____of___text
            if(sp_areas==0) sp_areas=1;
            int total_spaces=l-c_cnt,each_space_size=total_spaces/(sp_areas);
            int leftover=total_spaces-((sp_areas)*each_space_size);
            string ans,s;
            istringstream in(str);
                ans.append(each_space_size+(leftover-->0?1:0),' '); //put one space
            return ans.substr(0,l);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.