Leet Code 68 Text Justification - Java
2016-06-25 00:00
495 查看
摘要: Leet Code 68 Text Justification - Java
问题原始链接 https://leetcode.com/problems/text-justification
问题原始链接 https://leetcode.com/problems/text-justification
public class Solution { public static List<String> fullJustify(String[] words, int maxWidth) { List<String> result = new ArrayList<String>(); if (words == null || words.length == 0) { return result; } int start = -1; int length = 0; StringBuilder sb = new StringBuilder(); for (int i = 0; i < words.length; i++) { start = i; length = words[i].length(); while (i + 1 < words.length && length + 1 + words[i + 1].length() <= maxWidth) { length += 1 + words[i + 1].length(); i++; } if (i < words.length - 1) { if (start == i) { result.add(justifyOneWord(words, maxWidth, start, sb)); } else { result.add(justifyWords(words, maxWidth, length, start, i, sb)); } } else { result.add(justifyLastLine(words, maxWidth, start, i, sb)); } } return result; } private static String justifyOneWord(String[] words, int maxWidth, int i, StringBuilder sb) { sb.setLength(0); sb.append(words[i]); while (sb.length() < maxWidth) { sb.append(" "); } return sb.toString(); } private static String justifyWords(String[] words, int maxWidth, int length, int start, int end, StringBuilder sb) { sb.setLength(0); int spaces = (maxWidth - length) / (end - start); int left = (maxWidth - length) % (end - start); for (int j = start; j <= end; j++) { if (sb.length() > 0) { sb.append(" "); for (int k = 0; k < spaces; k++) { sb.append(" "); } if (j - start <= left) { sb.append(" "); } } sb.append(words[j]); } return sb.toString(); } private static String justifyLastLine(String[] words, int maxWidth, int start, int end, StringBuilder sb) { sb.setLength(0); for (int j = start; j <= end; j++) { if (sb.length() > 0) { sb.append(" "); } sb.append(words[j]); } while (sb.length() < maxWidth) { sb.append(" "); } return sb.toString(); } }
相关文章推荐
- text-align:justify实现文本两端对齐 兼容IE
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解