zoukankan      html  css  js  c++  java
  • Java for LeetCode 068 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.

    解题思路:

    直接按照约束条件老实实现即可,JAVA实现如下:

         static public List<String> fullJustify(String[] words, int maxWidth) {
            List<String> list=new ArrayList<String>();
            int start=0,end=-1,sum=0;
            for(int i=0;i<words.length;i++){
            	sum+=words[i].length();
            	if(sum>maxWidth){
            		i--;
            		start=end+1;
            		end=i;
            		sum=0;
            		list.add(oneString(words,start,end,maxWidth));
            		continue;
            	}
            	sum++;
            }
            if(sum>0)
            	list.add(oneString(words,end+1,words.length-1,maxWidth));
            return list;   
        }
        static public String oneString(String[] words,int start,int end,int maxWidth){
        	StringBuilder sb=new StringBuilder();
        	if(start==end)
        		sb.append(words[start]);
        	else if(end==words.length-1){
        		for(int i=start;i<=end-1;i++)
        			sb.append(words[i]+" ");
        		sb.append(words[end]);
        	}
        	else{
        	    int spaceSum=maxWidth;
        	    for(int i=start;i<=end;i++)
        		    spaceSum-=words[i].length();
        		int extra=spaceSum-(spaceSum/(end-start))*(end-start);
        		for(int i=start;i<=end;i++){
        			sb.append(words[i]);
        			for(int j=0;j<spaceSum/(end-start)&&i!=end;j++)
        				sb.append(" ");
        			if(extra-->0)
        				sb.append(" ");
        		}
        	}
        	while(sb.length()<maxWidth)
        		sb.append(" ");
        	return sb.toString();
        }
    
  • 相关阅读:
    利用jmeter+JAVA对RPC的单接口(dubbo接口等)进行性能测试
    spring mvc中,直接注入的HttpServletRequst是否安全呢?
    基础篇系列,JAVA的并发包
    撸基础篇系列,JAVA的NIO部分
    1, 本地缓存的实现以及遇到的问题
    python操作mysql数据库之pymysql
    软件测试中常见的一些经典Bug
    做性能测试前需要弄明白的几个知识点
    接口测试常见问题汇总
    用例中四大核心要素的写作规范
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4508338.html
Copyright © 2011-2022 走看看