C++ solution with comments


  • 2
    H
    vector<string> fullJustify(vector<string>& words, int maxWidth) {
          int idx = 0;
          vector<string> ret;
          while (idx < words.size()) {
            // get the current line
            int end = idx;
            int total = 0;
            vector<string> line;
            while (end < words.size() \
        	   && total+line.size()+words[end].length() <= maxWidth) {
              line.push_back(words[end]);
              total += words[end].length();
              end ++;
            }
            // the last line or just a single word -> left alignment
            // just pad the end with spaces
            string l = words[idx];
            if (end == words.size() || line.size()==1) {      
              for (int i = idx+1; i < end; i ++)
                l += " " + words[i];
              l += string(maxWidth-(total+line.size()-1), ' ');
            }
            // distribute the spaces evenly
            else {
              int space_len = maxWidth - total;
              int left = space_len % (line.size()-1);
              int base = space_len / (line.size()-1);
              int cnt = 0;
              for (int i = idx+1; i < end; i ++) {
                l += string(base, ' ');
                // add extra
                if (cnt < left) {
                  l += " ";
                  cnt ++;
                }
                l += words[i];
              }
            }
            ret.push_back(l);
            idx = end;
          }
          return ret;
    }

  • 0
    C

    Good Code.But I think maybe the vector<string> lineis not necessary.
    You can use end-startto get the line's size.


Log in to reply
 

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