2021-05-01(68. 文本左右对齐)

class Solution {
    public List<String> fullJustify(String[] words, int maxWidth) {
        List<String> list = new LinkedList<>();
        StringBuilder sb;
        int count = 0, i, j;
        for (i = 0, j = 0; i < words.length; i++) {
            if (count + words[i].length() + (i - j) > maxWidth) {
                int total = maxWidth - count;
                int each = i - j == 1 ? 0 : total / (i - j - 1);
                int last = i - j == 1 ? total : total - each * (i - j - 1);
                sb = new StringBuilder();
                for (int k = j; k < i - 1; k++) {
                    sb.append(words[k]);
                    for (int l = 0; l < each; l++) {
                        sb.append(" ");
                    }
                    if (last-- > 0) {
                        sb.append(" ");
                    }
                }
                sb.append(words[i - 1]);
                while (last-- > 0) {
                    sb.append(" ");
                }
                list.add(sb.toString());
                j = i;
                count = 0;
            }

            count += words[i].length();
        }
        sb = new StringBuilder();
        for (int k = j; k < i - 1; k++) {
            sb.append(words[k]).append(" ");
        }
        sb.append(words[i - 1]);
        while (sb.length() < maxWidth) {
            sb.append(" ");
        }
        list.add(sb.toString());
        return list;
    }
}

繁琐的题目,只想抄了

上一篇:递归


下一篇:Leetcode No.68 文本左右对齐(模拟)