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;
  • 相关阅读:
    [HDU2136] Largest prime factor(素数筛)
    [luoguP1082] 同余方程(扩展欧几里得)
    基本数论算法
    [luoguP2444] [POI2000]病毒(AC自动机 + dfs)
    [luoguP2564] [SCOI2009]生日礼物(队列)
    在EditText插入表情,并发送表情
    程序员自我提高的几点建议
    CSS3悬停特效合集Hover.css
    带动画效果的jQuery手风琴
    android程序的真正入口
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682124.html
Copyright © 2011-2022 走看看