zoukankan      html  css  js  c++  java
  • Text Justification

    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 L characters.
    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."]
    L: 16.
    Return the formatted lines as:
    [
    "This is an",
    "example of text",
    "justification. "
    ]
    Note: Each word is guaranteed not to exceed L in length.
    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.

    Solution: ...

     1 vector<string> res;
     2         int i = 0, N = words.size();
     3         while (i < N)
     4         {
     5             int length = words[i].size();
     6             int j = i + 1;
     7             while (j < N && length + words[j].size() + (j-i) <= L)
     8                 length += words[j++].size();
     9             // build line
    10             string s(words[i]);
    11             bool isLastLine = (j == N);
    12             bool oneWord = (j == i + 1);
    13             int average = isLastLine || oneWord ? 1 : (L - length) / (j - i - 1);
    14             int extra = isLastLine || oneWord ? 0 : (L - length) % (j - i - 1);
    15             for (int k = i + 1; k < j; ++k) {
    16                 s.append(extra > 0 ? average + 1 : average, ' ');
    17                 s.append(words[k]);
    18                 extra--;
    19             }
    20             s.append(L - s.size(), ' ');
    21             // push line
    22             res.push_back(s);
    23             i = j;
    24         }
    25         return res;
  • 相关阅读:
    敏捷开发第五天
    敏捷开发第四天
    系统用户分析模型
    第三天敏捷开发
    第二天敏捷开发
    敏捷开发第一天
    第三周学习总结
    [学习笔记]莫队算法
    【网络流】Modular Production Line
    [学习笔记]set的使用
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682124.html
Copyright © 2011-2022 走看看