[Leetcode 68, Hard] Text Justification

来源:互联网 发布:广州男装网络批发 编辑:程序博客网 时间:2024/09/21 08:56

Problem:

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 Lcharacters.

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."]
L16.

Return the formatted lines as:

[   "This    is    an",   "example  of text",   "justification.  "]

Note: Each word is guaranteed not to exceed L in length.

click to show corner cases.

Corner Cases:

  • A line other than the last line might contain only one word. What should you do in this case?
    In this case, that line should be left-justified.

Analysis:

The solution comes from http://blog.csdn.net/kenden23/article/details/17376113

Solutions:

C++:

    vector<string> fullJustify(vector<string>& words, int maxWidth)     {        vector<string> rs;        int L = maxWidth;                  for (int i = 0; i < words.size(); )          {              int j = i+1;              int len = words[i].length();              for (; j < words.size() && len+words[j].length()<L; j++)                  len += 1 + words[j].length();                            if (j == words.size())              {                  string s(words[i]);                  for (i++ ; i < j; i++) s +=" "+words[i];                  while (s.length() < L) s.push_back(' ');                  rs.push_back(s);                  return rs;              }              if (j-i == 1)               {                  rs.push_back(words[i++]);                  rs.back().append(L-rs.back().length(), ' ');                  continue;              }                int a = (L-len) / (j-i-1) + 1;              int b = (L-len) % (j-i-1);              string s(words[i]);              for (i++; i < j; i++, b--)              {                  s.append(a,' ');                  if (b>0) s.push_back(' ');                  s.append(words[i]);              }              rs.push_back(s);          }          return rs;    }
Java:


Python:

0 0
原创粉丝点击