leetcode 103: Text Justification (uncompleted.)

Text JustificationApr 3 '12

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.

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.

uncompleted.

 

 

public class Solution {
    public ArrayList<String> fullJustify(String[] words, int L) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<String> res = new ArrayList<String>();
    	if (words == null || L <= 0 || words[0].length() == 0)
			return res;

		int i = 0;
		while (i < words.length) {
			// greedy
			int j = 0;
			int sum = 0;
			// StringBuilder sb = new StringBuilder();
			while (i + j < words.length && sum + words[i + j].length() <= L) {
				sum += words[i + j].length() + 1;
				j++;
			}
			
			if (i + j == words.length){
				int k=0;
				StringBuilder sb = new StringBuilder();
				while(k<j){
					sb.append(words[i + k]);
					sb.append(' ');
					k++;
				}
				if(sb.length()<=L){
					sb.append(' ');
                    sb.append(' ');
				}
				res.add(sb.toString());
				return res;
			}
			if (j == 1) {
				StringBuilder sb = new StringBuilder(words[i]);
				char[] pad = new char[L-words[i].length()];
				Arrays.fill(pad, ' ');
				sb.append(pad);
				res.add(sb.toString());
				i = i + j;
				continue;
			}

			int num = sum - j;
			int space = L - num;
			int remains = space % j;
			int interval = space / j;

			StringBuilder sb = new StringBuilder();
			int k = 0;
			while (k < j) {
				sb.append(words[i + k]);
				for (int ii = 0; ii < interval; ii++) {
					sb.append(' ');
				}
				if (remains != 0) {
					sb.append(' ');
					--remains;
				}
				++k;
			}
			res.add(sb.toString());
			i = i + j;
		}
		return res;
    }
}




 

posted @ 2013-03-04 17:47  西施豆腐渣  阅读(163)  评论(0编辑  收藏  举报