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;
  • 相关阅读:
    shell脚本批量检查网站是否正常
    测试运维-linux中常用的操作命令以及工作思路
    软件自动化测试工程师面试题集锦(2)
    UI自动化测试常用操作函数(3)
    软件自动化测试工程师面试题集锦(1)
    UI自动化测试常用操作函数(2)
    UI自动化测试常用操作函数(1)
    滑屏找元素
    代码报错解析
    心情20.4.6
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3682124.html
Copyright © 2011-2022 走看看