|
| 1 | +package com.interview.array; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.List; |
| 5 | + |
| 6 | +/** |
| 7 | + * Date 03/12/2016 |
| 8 | + * @author Tushar Roy |
| 9 | + * |
| 10 | + * Given an array of words and a length L, format the text such that each line has exactly L characters and is fully |
| 11 | + * (left and right) justified. |
| 12 | + * You should pack your words in a greedy approach; that is, pack as many words as you can in each line. |
| 13 | + * |
| 14 | + * Time complexity - O(n) where n is the number of words |
| 15 | + * Space complexity - O(1) |
| 16 | + * |
| 17 | + * https://leetcode.com/problems/text-justification/ |
| 18 | + */ |
| 19 | +public class GreedyTextJustification { |
| 20 | + public List<String> fullJustify(String[] words, int maxWidth) { |
| 21 | + List<String> result = new ArrayList<>(); |
| 22 | + for (int i = 0; i < words.length; ) { |
| 23 | + int total = words[i].length(); |
| 24 | + int j = i + 1; |
| 25 | + StringBuffer buff = new StringBuffer(); |
| 26 | + buff.append(words[i]); |
| 27 | + while(j < words.length && total + words[j].length() + 1 <= maxWidth) { |
| 28 | + total += words[j].length() + 1; |
| 29 | + j++; |
| 30 | + } |
| 31 | + int remaining = maxWidth - total; |
| 32 | + //since j is not word length means its not a last line. So pad accordingly. |
| 33 | + if (j != words.length) { |
| 34 | + int count = j - i - 1; |
| 35 | + if (count == 0) { |
| 36 | + padSpace(buff, remaining); |
| 37 | + } else { |
| 38 | + int q = remaining/count; |
| 39 | + int r = remaining % count; |
| 40 | + for (int k = i + 1; k < j; k++) { |
| 41 | + padSpace(buff, q); |
| 42 | + if (r > 0) { |
| 43 | + buff.append(" "); |
| 44 | + r--; |
| 45 | + } |
| 46 | + buff.append(" ").append(words[k]); |
| 47 | + } |
| 48 | + } |
| 49 | + } else { //if it is last line then left justify all the words. |
| 50 | + for (int k = i + 1; k < j; k++) { |
| 51 | + buff.append(" ").append(words[k]); |
| 52 | + } |
| 53 | + padSpace(buff, remaining); |
| 54 | + } |
| 55 | + result.add(buff.toString()); |
| 56 | + i = j; |
| 57 | + } |
| 58 | + return result; |
| 59 | + } |
| 60 | + |
| 61 | + private void padSpace(StringBuffer buff, int count) { |
| 62 | + for (int i = 0; i < count; i++) { |
| 63 | + buff.append(" "); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + public static void main(String args[]) { |
| 68 | + String[] input = {"What","must","be","shall","be."}; |
| 69 | + GreedyTextJustification gtj = new GreedyTextJustification(); |
| 70 | + List<String> result = gtj.fullJustify(input, 12); |
| 71 | + System.out.print(result); |
| 72 | + } |
| 73 | +} |
0 commit comments