zoukankan      html  css  js  c++  java
  • Text Justification

     1 public class Solution {
     2     public ArrayList<String> fullJustify(String[] words, int L) {
     3         // IMPORTANT: Please reset any member data you declared, as
     4         // the same Solution instance will be reused for each test case.
     5         int wordsCount = words.length;
     6         ArrayList<String> result = new ArrayList<String>();
     7         int curLen = 0;
     8         int lastI = 0;
     9         for (int i = 0; i <= wordsCount; i++) {
    10             if (i == wordsCount || curLen + words[i].length() + i - lastI > L) {
    11                 StringBuffer buf = new StringBuffer();
    12                 int spaceCount = L - curLen;
    13                 int spaceSlots = i - lastI - 1;
    14                 if (spaceSlots == 0 || i == wordsCount) {
    15                     for(int j = lastI; j < i; j++){
    16                         buf.append(words[j]);
    17                         if(j != i - 1)
    18                             appendSpace(buf, 1);
    19                     }
    20                     appendSpace(buf, L - buf.length());
    21                 } else {
    22                     int spaceEach = spaceCount / spaceSlots;
    23                     int spaceExtra = spaceCount % spaceSlots;
    24                     for (int j = lastI; j < i; j++) {
    25                         buf.append(words[j]);
    26                         if (j != i - 1)
    27                             appendSpace(buf, spaceEach + (j - lastI < spaceExtra ? 1 : 0));
    28                     }
    29                 }
    30                 result.add(buf.toString());
    31                 lastI = i;
    32                 curLen = 0;
    33             }
    34             if (i < wordsCount)
    35                 curLen += words[i].length();
    36         }
    37         return result;
    38     }
    39 
    40     private void appendSpace(StringBuffer sb, int count) {
    41         for (int i = 0; i < count; i++)
    42             sb.append(' ');
    43     }
    44 }
  • 相关阅读:
    JavaScript对象 原型
    JavaScript数据类型 数据转换
    JavaScript字符串去除空格
    JavaScript实现StringBuffer
    JavaScript获取url参数
    JavaScript获取当前根目录
    React 和 Redux理解
    Umbraco 中获取一个media item的文件路径 file path
    Umbraco中获取UmbracoContext
    Umbraco中如何找到home node
  • 原文地址:https://www.cnblogs.com/jasonC/p/3436757.html
Copyright © 2011-2022 走看看