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;
  • 相关阅读:
    H264源码分析(四)
    矩阵在编程中的一个小应用
    android listview 三种适配器设置
    Android SoundPool 的使用以及原理分析
    poj 2728 Desert King(最优比例生成树)
    MySQL 查询结果以百分比显示
    Android Application
    飘逸的python
    CSS教程:div垂直居中的N种方法[转]
    HQL: Hibernate查询语言
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682124.html
Copyright © 2011-2022 走看看