My simple 0ms C++ code (~20 lines)

  • 0

    Just a straightforward solution. start is the starting index of words and from start, we try to pack as many as possible words in a line and wCount is the number of words we can pack in the current line. curL is the sum of those wCount words. After we get wCount and curL, then we output the current line. There are two cases

    1. only one word in the current line or the current one is the last line. Then we just put one space to separate two consecutive words and put the rest of spaces at the end.

    2. otherwise, we will calculate spaceNum and leftS (i.e. for the first leftS+1 words, we will put spaceNum+1 spaces in between of two words, for the rest, we will put spaceNum spaces to separate words)

      class Solution {
      vector<string> fullJustify(vector<string>& words, int maxWidth) {
      vector<string> res;
      int wSize = words.size(), start=0, wCount =0, curL, i, leftS, spaceNum;
      while(start < wSize)
      { //count how many words can be packed in the current line
      for(curL = 0, wCount =0; (start+wCount <wSize) && (curL+words[start+wCount].size() + wCount<=maxWidth);) curL += words[start+wCount++].size();
      if(wCount==1 || (start+wCount) == wSize)
      { //case (1), only one space in between of two consecutive words
      for(i=1;i<wCount;++i) res.back() += words[start++] + " ";
      res.back() += words[start++] + string(maxWidth- res.back().size()- words[start].size(), ' ');
      { // case (2),
      spaceNum = (maxWidth - curL) / (wCount-1);
      leftS = (maxWidth - curL) % (wCount-1);
      res.back() +=words[start++];
      for(i=0; i<leftS; ++i) res.back() += string(spaceNum+1, ' ') + words[start++];
      for(wCount -=(leftS+1); wCount>0; --wCount) res.back() += string(spaceNum, ' ') + words[start++];
      return res;

Log in to reply

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