LeetCode068 Text Justification

详细见:leetcode.com/problems/text-justification


Java Solution: github

package leetcode;

import java.util.LinkedList;
import java.util.List;

/*
 * 	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.
 * 	
 */


public class P068_TextJustification {
	public static void main(String[] args) {
		List<String> ans = new Solution1().fullJustify(new String[]{"a"}, 1);
		tools.Utils.B_打印List_String(ans);
	}
	/*
	 * 	1 ms
	 * 	又是一个试错AC
	 * 	这里的逻辑本身非常复杂
	 */
	static class Solution1 {
		int[] len = null;
	    public List<String> fullJustify(String[] words, int maxWidth) {
			List<String> ans = new LinkedList<String>();
	    	if (words == null || words.length == 0)
	    		return ans;
	    	if (maxWidth == 1 && words.length == 1 && words[0].equals("")) {
	    		ans.add("");
	    		return ans;
	    	}
	    	len = new int[words.length];
	    	char[] cs = new char[maxWidth];
	    	for (int i = 0; i != len.length; i ++)
	    		len[i] = words[i] == null ? 0 : words[i].length();
	    	int sum = 0, index = -1, preIndex = 0;
	    	while (++ index != words.length) {
	    		if (index == words.length - 1) {
	    			if (sum + len[index] <= maxWidth) {
	    				int i = 0;
	    				for (int j = preIndex; j <= index; j ++) {
	    					for (int k = 0; k != len[j]; k ++)
	    						cs[i ++] = words[j].charAt(k);
	    					if (i < maxWidth)
	    						cs[i ++] = ' ';
	    				}
	    				while (i < maxWidth)
	    					cs[i ++] = ' ';
	    				ans.add(new String(cs));
	    			} else {
	    				ans.add(generateString(words, preIndex, index - 1, sum - 1, maxWidth, cs));
	    				for (int i = 0; i != maxWidth; i ++)
	    					cs[i] = i < len[index] ? words[index].charAt(i) : ' ';
	    				ans.add(new String(cs));
	    			}
	    			break;
	    		}
	    		if (sum + len[index] == maxWidth || sum + len[index] + 1 == maxWidth) {
	    			ans.add(generateString(words, preIndex, index, sum + len[index], maxWidth, cs));
	    			sum = 0;
	    			preIndex = index + 1;
	    		} else if (sum + len[index] + 1 < maxWidth) {
	    			sum += len[index] + 1;
 	    		} else {
	    			//	sum + len[index] + 1 > maxWidth
	    			ans.add(generateString(words, preIndex, index - 1, sum - 1, maxWidth, cs));
	    			sum = len[index] + 1;
	    			preIndex = index;
	    		}
	    	}
	        return ans;
	    }
	    private String generateString(String[] words, int preIndex, int newIndex, int sum, int maxWidth, char[] cs) {
	    	if (newIndex == preIndex) {
	    		for (int i = 0; i != maxWidth; i ++)
	    			cs[i] = i < len[preIndex] ? words[preIndex].charAt(i) : ' ';
	    		return new String(cs);
	    	}
	    	int allBlank = maxWidth;
	    	for (int i = preIndex; i <= newIndex; i ++)
	    		allBlank -= len[i];
	    	int blank = allBlank / (newIndex - preIndex);
	    	int moreBlank = allBlank % (newIndex - preIndex) + preIndex;
	    	int i = 0;
	    	for (int index = preIndex; index <= newIndex; index ++) {
	    		int thisBlank = blank + (index < moreBlank ? 1 : 0);
	    		for (int j = 0; j < len[index]; j ++)
	    			cs[i ++] = words[index].charAt(j);
	    		for (int j = 0; index != newIndex && j != thisBlank; j ++)
	    			cs[i ++] = ' ';
	    	}
	    	return new String(cs);
	    }
	}
}


C Solution: github

/*
    url: leetcode.com/problems/text-justification
    AC 3ms 0.00%
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//array_list start

typedef char* T;
typedef struct al sal;
typedef struct al * pal;

struct al {
    int capacity;
    int size;
    T* arr;
};

pal al_init(int capacity) {
    pal l = (pal) malloc(sizeof(sal));
    if (capacity < 1) return NULL;
    l->arr = (T*) malloc(sizeof(T) * capacity);
    l->capacity = capacity;
    l->size = 0;
    return l;
}

void al_expand_capacity(pal l) {
    T* new_arr = (T*) malloc(sizeof(T) * (l->capacity * 2 + 1));
    int i = 0;
    for (i = 0; i < l->capacity; i ++)
        new_arr[i] = l->arr[i];
    free(l->arr);
    l->arr = new_arr;
    l->capacity = l->capacity * 2 + 1;
}

void al_add_last(pal l, T v) {
    if (l->capacity == l->size) al_expand_capacity(l);
    l->arr[l->size] = v;
    l->size ++;
}

void al_add_to_index(pal l, T v, int index) {
    int i = 0;
    if (index > l->size) return;
    if (l->capacity == l->size) al_expand_capacity(l);
    for (i = l->size - 1; i >= index; i --) {
        l->arr[i+1] = l->arr[i];
    }
    l->arr[index] = v;
    l->size ++;
}

T* al_convert_to_array_free_l(pal l) {
    T* arr = l->arr;
    free(l);
    return arr;
}

void al_print(pal l) {
    int i = 0;
    if (l->size == 0) return;
    for (i = 0; i < l->size; i ++)
        printf("%s \r\n", l->arr[i]);
    printf("\r\n");
}

//array_list end


char** fullJustify(char** ws, int wn, int mw, int* rn) {
    int wi = 0, ci = 0, nw = 0, i = 0, bn = 0;
    int j = 0, ai = 0, jn = 0;
    char* a = NULL;
    pal l = al_init(16);
    int* wl = (int*) malloc(sizeof(int) * wn);
    for (i = 0; i < wn; i ++)
        wl[i] = strlen(ws[i]);
    while (wi < wn) {
        ci = 1;
        i = wi;
        nw = strlen(ws[wi]);
        a = (char*) malloc(sizeof(char) * (mw+1));
        ai = 0;
        a[mw] = '\0';
        while (wi+1 != wn && nw+wl[wi+1]+1 <= mw) {
            nw += wl[wi+1]+1;
            wi ++;
            ci ++;
        }
        wi ++;
        bn = mw-nw+ci-1;
        for (; i < wi; i ++) {
            for (j = 0; j < wl[i]; j ++)
                a[ai++] = ws[i][j];
            if (i != wi-1) {
                jn = bn / (ci-1) + (bn % (ci-1) == 0 ?  0 : 1);
                if (wi == wn) jn = 1;
                for (j = 0; j < jn; j ++)
                    a[ai++] = ' ';
                bn -= jn;
                ci --;
            } else {
                while (ai < mw)
                    a[ai++] = ' ';
            }
        }
        
        al_add_last(l, a);
    }
    *rn = l->size;
    return al_convert_to_array_free_l(l);
}

int main() {
    int wn = 7;
    char** ws = (char**) malloc(sizeof(char*) * wn);
    char** ans = NULL;
    int mw = 12;
    int rn = 0;
    int i = 0;

    ws[0] = "what";
    ws[1] = "must";
    ws[2] = "be";
    ws[3] = "shall";
    ws[4] = "be.";
    ws[5] = "text";
    ws[6] = "justification.";
    ans = fullJustify(ws, 5, mw, &rn);
    for (i = 0; i < rn; i ++) {
        printf("%s\tlen is %d\r\n", ans[i], strlen(ans[i]));
        free(ans[i]);
    }
    free(ans);
    free(ws);
    return 0;
    
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/text-justification/
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月15日
    @details:    Solution: 55ms 25.07%
'''

class Solution(object):
    def fullJustify(self, ws, mw):
        """
        :type ws: List[str]
        :type mw: int
        :rtype: List[str]
        """
        wn = 0 if ws == None else len(ws)
        if wn == 0: return [""]
        ans, s, pi  = [], 0, 0
        for i in range(wn):
            if s+len(ws[i])+1 > mw and i != pi:
                b_num = mw - s + i-1 -pi
                if pi == i-1:
                    ans.append(ws[pi]+(" "*b_num))
                else:
                    ans_t = ""
                    for j in range(pi, i):
                        ans_t += ws[j]
                        if b_num > 0 and i-1-j != 0:
                            b_this = 0 if b_num % (i-1-j) == 0 else 1
                            b_this += b_num // (i-1-j)
                            ans_t += (" " * b_this)
                            b_num -= b_this
                    ans.append(ans_t)
                s = len(ws[i])
                pi = i
            else:
                if s == 0:
                    s = len(ws[i])
                else:
                    s += (1 + len(ws[i]))
        b_num, ans_t = mw - s + wn-1 -pi, ""
        for i in range(pi, wn):
            if i != pi: ans_t += " "
            ans_t += ws[i]
        ans_t += " " * (mw - len(ans_t))
        ans.append(ans_t)
        return ans

if __name__ == "__main__":
    ws = ["This", "is", "an", "example", "of", "text", "justification."]
    ws = ["This", "is"]
    ws = ["b", "c", "e", "f"]
    mw = 1
    for s in Solution().fullJustify(ws, mw):
        print(s)
        print(len(s))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值