`
xitonga
  • 浏览: 588239 次
文章分类
社区版块
存档分类
最新评论

Text Justification 文本对齐 @LeetCode

 
阅读更多

快被这道题搞死了。。

根据这篇重写了http://www.cnblogs.com/TenosDoIt/p/3475275.html

分析:这一题需要注意两个点,a、当该行只放一个单词时,空格全部在右边 b、最后一行中单词间只有一个空格,其余空格全部在右边。然后只要贪心选择,在一行中尽量放多的单词。


package Level4;

import java.util.ArrayList;

/**
Text Justification 

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.
 */
public class S68 {

	public static void main(String[] args) {
		 String[] words = {"This", "is", "an", "example", "of", "text", "justification."};
//		 String[] words = {""};
//		 String[] words = {"What","must","be","shall","be."};
//		String[] words = { "" };
		int L = 16;
		System.out.println(fullJustify(words, L));
	}

	
	public static ArrayList<String> fullJustify(String[] words, int L) {
		ArrayList<String> ret = new ArrayList<String>();
		int wordsLen = words.length;	// 单词数组的长度
		int curWordIdx = 0;		// 处理第i个单词
		while(curWordIdx < wordsLen){		// 处理完所有单词后退出
			int charLen = 0;  // 当前行累积的字符数量
			int probeWordIdx = curWordIdx;
			while(probeWordIdx<wordsLen && charLen+words[probeWordIdx].length()<=L){	// 贪婪加入尽可能多的单词
				charLen += ((words[probeWordIdx++]).length()+1);		// 累积单词长度和至少要有一个空格
			}
			if(probeWordIdx-curWordIdx == 1){		// tmpWordIdx-curWordIdx: 该行放入单词的数目,如果只有一个单词要特殊处理
				String tmp = words[curWordIdx];	// 唯一的那个单词
				tmp = addSpace(tmp, L-words[curWordIdx].length());	// 那个单词后面都接上空格
				ret.add(tmp);
				curWordIdx = probeWordIdx;		// 更新curWordIdx,因为已经处理好当前行了
				continue;
			}
			
			// tmpWordIdx-curWordIdx: 该行放入单词的数目,也就是紧接的空格的数量(因为每个单词后接一个空格)
			// wordCharLen:当前行所有由单词组成的字符数量(不包括空格)
			int wordCharLen = charLen - (probeWordIdx-curWordIdx);		
			//meanSpace: 平均每个单词后的空格,tmpWordIdx<wordsLen 表示不是最后一行
			int meanSpace = probeWordIdx<wordsLen ? (L-wordCharLen)/(probeWordIdx-curWordIdx-1) : 1;
			//leftSpace: 多余的空格
			int leftSpace = probeWordIdx<wordsLen ? (L-wordCharLen)%(probeWordIdx-curWordIdx-1) : L-wordCharLen-(probeWordIdx-curWordIdx-1);
			String tmp = new String();
			for(int k=curWordIdx; k<probeWordIdx-1; k++){	// 对当前行最后一个单词特殊处理
				tmp += words[k];
				tmp = addSpace(tmp, meanSpace);
				if(probeWordIdx<wordsLen && leftSpace>0){	// 因为居中对齐
					tmp += " ";
					leftSpace--;
				}
			}
			tmp += words[probeWordIdx-1];		// 处理当前行的最后一个单词
			if(leftSpace > 0){		// 因为左对齐,所以在最后补上剩下的空格
				tmp = addSpace(tmp, leftSpace);
			}
			ret.add(tmp);
			curWordIdx = probeWordIdx;		// 处理下一行的要处理的单词
		}
		return ret;
	}
	
	public static String addSpace(String s, int count){
		for(int i=1; i<=count; i++){
			s += " ";
		}
		return s;
	}
	
	// ============================================
	
	
	// Bad attempt!
//	public static ArrayList<String> fullJustify2(String[] words, int L) {
//		int letterCnt = 0;
//		int wordCnt = 0;
//		for (String s : words) {
//			letterCnt += s.length(); // 计算字符总数
//		}
//
//		ArrayList<String> ret = new ArrayList<String>();
//		// if(L != 1){
//		// cnt = cnt + cnt-1;
//		// }
//		// System.out.println(cnt);
//		// int lines = (int) Math.ceil(1.0*cnt/L);
//		// System.out.println(lines);
//
//		int curWord = 0;
//		int oldWord = 0;
//		int totalWords = words.length;
//		while (true) {
//			letterCnt = 0;
//			wordCnt = 0;
//			curWord = oldWord;
//			while (curWord < words.length) {
//				letterCnt += words[curWord].length() + 1;
//				if (letterCnt > L + 1) { // 超过长度限制
//					break;
//				}
//				wordCnt += words[curWord].length(); // 计算总共单词个数
//				curWord++;
//			}
//			curWord--;
//			String s = "";
//			// System.out.println(wordCnt);
//			int totalSpaces = L - wordCnt; // 空格总数
//			int perSpaces = 0; // 每行的空格数目s
//			// if(j-oldj != 0){
//			perSpaces = (int) Math.ceil(1.0 * (L - wordCnt)
//					/ ((curWord - oldWord + 1) - 1));
//			// }
//
//			if (totalWords <= 0) {
//				break;
//			}
//			// System.out.println("totalSpaces:"+totalSpaces);
//			// System.out.println("perSpaces:"+perSpaces);
//			for (int k = oldWord; k <= curWord; k++) {
//				s += words[k];
//				if (totalWords == L && k == oldWord && totalSpaces != 0) {
//					s += " ";
//					totalSpaces -= 1;
//				} else {
//					if (perSpaces <= totalSpaces) {
//						for (int m = 0; m < perSpaces; m++) {
//							s += " ";
//						}
//						totalSpaces -= perSpaces;
//					} else {
//						for (int m = 0; m < totalSpaces; m++) {
//							s += " ";
//						}
//						totalSpaces -= totalSpaces;
//					}
//				}
//			}
//
//			totalWords -= (curWord - oldWord + 1);
//
//			ret.add(s);
//			oldWord = curWord + 1;
//		}
//		return ret;
//	}

	

}


分享到:
评论

相关推荐

    LeetCode最全代码

    # [LeetCode](https://leetcode.com/problemset/algorithms/) ![Language](https://img.shields.io/badge/language-Python%20%2F%20C++%2011-orange.svg) [![License]...

    python 实现文本左右对齐

    # 给定一个单词数组和一个长度 maxWidth,重新排版单词,使其成为每行恰好有 maxWidth 个字符,且左右两端对齐的文本 # 你应该使用“贪心算法”来放置给定的单词;也就是说,尽可能多地往每行中放置单词。必要时可用...

    电子商务英文课件:ch14 Economics and Justification of.ppt

    电子商务英文课件:ch14 Economics and Justification of.ppt

    hyphenation-justification-vf

    看一下换行和对齐方式,以及可变字体如何改善对齐文本。 在2018年Robothon大会上演示了使用可变字体改善对齐方式的演示。 如何使用 带上自己的可变字体。 :)代码引用了Gimlet可变字体,但是出于许可的原因,不包含...

    Use TOC and ROI for justification

    这个文档讲述了如何通过TOC和ROI来判断是否进行投资,同样可以通过这一点来说服企业管理层

    《天线手册》【美国海军版】.PDF

    全英文,To Our Readers Changes: Readers of this publication are encouraged to submit suggestions and changes that will improve it. Recommendations ...• Justification and/or source of change

    摩托罗拉XTS3000写频软件

    :用于选择文本的对齐方式(左对齐或右对齐) 。 Channel Text Size :信道文本长度(与区域文本共享 14 位字符,设置得长,区域文本长度就要缩减。 ) Zone Text Size :区域文本长度。 Slow ...

    LaTeX Beginner's Guide——Stefan Kottwitz

    4.Apply intelligent justification and customized hyphenation to achieve fine text design 5.Typeset professional-looking tables and create bulleted and enumerated lists 6.Write sophisticated math ...

    Agg的.NET移植Agg-Sharp.zip

    AddChild(new TextWidget("Hello World", 320, 240, justification: Font.Justification.Center)); ShowAsSystemWindow(); } // and just for fun lets also draw a circle public ...

    Android代码-TextJustify-Android

    Android Full Justification About This library will provide you a way to justify text. It supports both plain text and Spannables. Additionally, the library can auto-hyphentate your displayed content ...

    cpp-算法精粹

    Text Justification Max Points on a Line Community QQ 群: 237669375 Github: https://www.github.com/soulmachine/algorithm-essentials 微博: @灵魂机器 License Book License: CC BY-SA 3.0 License

    Fundamental Networking in Java

    " 1.4 provide further justification for the appearance of this text. Much of the information in this book is either absent from or incorrectly specified in the Java documentation and books by other ...

    机器学习经典制作(英语)

    for the discussion and justification of algorithms. It also describes several key aspects of the application of these algorithms. We have aimed to present the most novel theoretical tools and concepts...

    VB编程资源大全(英文源码 其它)

    This is used to make 3D text.&lt;END&gt;&lt;br&gt;27 , basMath.zip This module contains functions for various math equations. &lt;END&gt;&lt;br&gt;28 , calc.zip This is a basic calculator written in Visual Basic.&lt;END&gt;...

    Pattern-Oriented+Software+Architecture+(Vol.5).pdf

    justification. But design: what happens when we design? Is design about problems or about beauty? Does resolving forces while solving a problem force beauty into the design? Or can beauty and ideal ...

    CS229 Supplemental Lecture notes John Duchi

    is somewhat different from the original interpretation and justification of Freund and Schapire, but which lends itself to our approach of (1) choose a representation, (2) choose a loss, and (3) ...

    2022美赛备赛之论文写作.pdf

    目录 一、Summary 二、introduction Problem Background Problem restatememt Literature review Our work ...三、假设Assumptions and Justification ...三、假设Assumptions and Justification

    2016年上午基础知识.pdf

    The pragmatic justification for this approach is that it is easier to achieve ( 71 ) on small steps, whereas it is much harder to get everyone on board if too much is attempted. Usually there are ...

    Geometric Description of Images as Topographic Maps (Lecture Notes in Mathematics) By Vicent Caselles, Pascal Monasse

    Computer scientists will find algorithmic considerations in Chapters 6 and 7, the full justification of which may be found in Chapters 2 and 4 respectively. Lastly, all readers can learn more about ...

    exetreme value

    In this chapter, we briefly present some of the key results of extreme value theory, which provide a statistical justification for the emergence of power laws as limiting behavior for extreme ...

Global site tag (gtag.js) - Google Analytics