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 }
  • 相关阅读:
    关于在Websphere下程序找不到jar包内.properties文件的问题
    MysqL的root用户不允许远程连接
    ajax提交表单数据到controller
    js表单验证
    jq删除标签中的元素
    点击超链接触发js事件
    spring的特点
    mysql每个jar包的作用
    抽象工厂举例
    简单的省市联动
  • 原文地址:https://www.cnblogs.com/jasonC/p/3436757.html
Copyright © 2011-2022 走看看