(Java)LeetCode-68. Text Justification

本文介绍了一种文本两端对齐的算法实现,该算法能够确保每行文本在给定宽度下,通过合理分配空格使得文本既美观又符合格式要求。文章详细解释了算法的工作原理,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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."]
L16.

Return the formatted lines as:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

Note: Each word is guaranteed not to exceed L in length.

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.

这道题呢,是hard模式,其实是不难的,就是比较繁琐,需要注意的细节比较多,比较考验编程细节问题吧。
首先是要判断出每一行有哪几个单词。
其实是要计算出这几个单词中分别隔着几个空格。
要注意的就是如果这一行只有一个单词,那就需要左对齐,
或者到了最后一行,那就需要每个单词之间只有一个空格,当然后面还是要空格补齐。

在计算一行中单词之间各有几个间隔时候,刚开始我想错了,比如说有七个空格,五个位置,那不可以是3,1,1,1,1 而需要是2,2,1,1,1  这一点需要注意。

代码如下:
public List<String> fullJustify(String[] words, int maxWidth) {
		List<String> result = new ArrayList<String>();  // store the result
		List<String> list = new ArrayList<String>();  //store the words in the same line
		
		int cnt = words[0].length();
		list.add(words[0]);
		int temp = 0;
		for(int i = 1; i < words.length; i++){
			temp = words[i].length() ;
			if(cnt + temp + 1 <= maxWidth){
				cnt += temp+1;
				list.add(words[i]);
			}else{
				cnt = temp;
				result.add(justify(list, maxWidth));
				list.clear();
				list.add(words[i]);
				
			}
		}
		if(list.size() > 0){   // handle the last line,it won't be handled in the preceding cycle
			int size = list.size();
			int c = 1;
			StringBuilder sb = new StringBuilder();
			for(String str : list){
				if(c++ == size){
					sb.append(str);
				}else{
					sb.append(str).append(" ");
				}
			}
			int remain = maxWidth - sb.length();
			for(int i = 0; i < remain; i++){
				sb.append(" ");
			}
			result.add(sb.toString());
		}
        return result;
    }
	
	//parameter : words in a line and the maxWidth
	//return the sentence after justifying
	private String justify(List<String> words, int maxWidth){
		int cnt = words.size()-1;
		int spaceLen = maxWidth;
		for(String word : words){
			spaceLen -= word.length();
		}
		StringBuilder sb = new StringBuilder();
		if(cnt == 0){
			sb.append(words.get(0));
			for(int i = 0; i < spaceLen; i++){
				sb.append(" ");
			}
			return sb.toString();
		}
		int tempSpaceLen = spaceLen;
		int tempCnt = cnt;
		int[] spaces = new int[cnt];   //store the number of spaces
		for(int i = 0; i < cnt; i++){
			if(tempSpaceLen % tempCnt != 0){
				spaces[i] = tempSpaceLen / tempCnt + 1;
				tempSpaceLen -= spaces[i];
				tempCnt--;
			}else{
				spaces[i] = tempSpaceLen / tempCnt;
			}
		}
		int temp = 0;
		for(String word : words){ // create the justified sentence
			if(temp == cnt){
				sb.append(word);
				break;
			}
			sb.append(word);
			for(int i = 0; i < spaces[temp]; i++){
				sb.append(" ");
			}
			temp++;
		}
		return sb.toString();
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值