leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

0068.cpp (1529B)


      1 class Solution {
      2   public:
      3     vector<string> fullJustify(vector<string> &words, int maxWidth) {
      4         vector<string> res;
      5         int i = 0, j;
      6         while (i < words.size()) {
      7             int count = words[i].size(); // character count
      8             for (j = i + 1; j < words.size() && count <= maxWidth; j++)
      9                 count += words[j].size() + 1; // word lenght + at least 1 space
     10 
     11             if (count > maxWidth) count -= words[--j].size() + 1; // if we overshot, remove last word
     12             int wordc = j - i;                                    // number of words for the current row
     13             count -= wordc - 1;           // remove minimum padding added from the character count;
     14             int white = maxWidth - count; // how much whitespace
     15             string row = words[i++];
     16             if (i != j) {
     17                 if (j != words.size()) {
     18                     while (i < j) {
     19                         int segment = ceil((double)white / (wordc-- - 1));
     20                         row += string(min(segment, white), ' ') + words[i++];
     21                         white -= segment;
     22                     }
     23                 } else {
     24                     // last row, adjust left
     25                     while (i < j)
     26                         row += " " + words[i++];
     27                 }
     28             }
     29             row += string(maxWidth - row.size(), ' '); // padd the remainder of the row
     30             res.push_back(row);                        // push the current row to the result
     31         }
     32         return res;
     33     }
     34 };