LeetCode Text Justification

来源:互联网 发布:安卓软件编辑器 编辑:程序博客网 时间:2024/05/22 10:35

Description:

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 exactlyL 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.


Solution:

纯模拟的感觉

注意一下最后一行每个单词之间就空一格


<span style="font-size:18px;">import java.util.*;public class Solution {public List<String> fullJustify(String[] words, int maxWidth) {List<String> list = new ArrayList<String>();int n = words.length;if (n == 0)return list;int pre_start = 0, current_wid = words[0].length();for (int i = 1; i <= n; i++) {if (i < n) {if (current_wid + 1 + words[i].length() <= maxWidth) {current_wid += 1 + words[i].length();} else {String str = makeSentence(words, pre_start, i, current_wid,maxWidth, false);list.add(str);current_wid = words[i].length();pre_start = i;}} else {String str = makeSentence(words, pre_start, i, current_wid,maxWidth, true);list.add(str);}}return list;}public String makeSentence(String words[], int start, int end,int current_width, int maxWidth, boolean lastLine) {String str = "";int segNum = end - start - 1;int sumWordsLen = current_width - segNum;int sumVacLen = maxWidth - sumWordsLen;int curVacLen;char[] temp;String tstr;for (int i = start; i < end; i++) {str = str + words[i];if (segNum > 0) {if (lastLine)curVacLen = 1;elsecurVacLen = (int) (Math.ceil(1.0 * sumVacLen / segNum));sumVacLen -= curVacLen;temp = new char[curVacLen];Arrays.fill(temp, ' ');tstr = new String(temp);str = str + tstr;segNum--;}}if (sumVacLen > 0) {curVacLen = sumVacLen;temp = new char[curVacLen];Arrays.fill(temp, ' ');tstr = new String(temp);str = str + tstr;}return str;}}</span>


0 0
原创粉丝点击