【LeetCode】Text Justification

来源:互联网 发布:爱他美淘宝网 编辑:程序博客网 时间:2024/05/29 04:45
Text Justification 
Total Accepted: 4114 Total Submissions: 29977 My Submissions
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.
click to show corner cases.
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.
这道题本意不难,但是表达繁琐,需要注意的是:
1、每行长度为L,行数肯定是不确定的。
2、如果空格比单词数要多,那么左边的空格比右边多。如示例中的第二行,有3个空格,左边是2个右边是3个。
3、最后一行,单词间都是一个空格。
4、如果每行一个单词的话,左对齐。
基本的思路不难,但是要考虑的细节比较多。代码逻辑不是很好,供参考吧。
思路写在代码中。

Java AC

public class Solution {    private int len;public ArrayList<String> fullJustify(String[] words, int L) {ArrayList<String> list = new ArrayList<String>();len = words.length;//统计每个单词的长度int numArr[] = new int[len];for (int i = 0; i < len; i++) {numArr[i] = words[i].length();}dfs(list, words, numArr, 0, L);//处理最后一行字符,中间只包含一个空格int size = list.size();String lastLine = list.get(size - 1);list.remove(size-1);lastLine = lastLine.trim().replaceAll("[ ]+", " ");int len = lastLine.length();while (len < L) {lastLine += " ";len++;}list.add(lastLine);return list;}private void dfs(ArrayList<String> list, String[] words, int[] numArr,int start, int l) {if (start >= len) {return;}//统计每行最多可以存放几个单词,长度是多少.int tempLen = 0;int i = start;while (i < len && tempLen < l) {tempLen += numArr[i];tempLen += 1;i++;}if (i != start) {i--;}if (tempLen > l+1) {tempLen -= numArr[i];tempLen -= 1;i -= 1;}int wordNum = i - start + 1;StringBuilder sb = new StringBuilder();//这里主要为了处理出现的字符为""if (tempLen == 0) {sb.append(words[start]);for (int j = 0; j < l; j++) {sb.append(" ");}}else {tempLen -= wordNum;int leftNum = l - tempLen;//单词数为1,不需要处理空格问题.if (wordNum == 1) {sb.append(words[start]);for (int j = 0; j < leftNum; j++) {sb.append(" ");}}else {//分布空格int num1 = leftNum / (wordNum - 1);int num2 = leftNum % (wordNum - 1);for (int j = start; j < i; j++) {sb.append(words[j]);int k = 0;while (k < num1) {sb.append(" ");k++;}if (num2 > 0) {sb.append(" ");num2--;}}sb.append(words[i]);}}list.add(sb.toString());dfs(list, words, numArr, i+1, l);}}


0 0
原创粉丝点击