LinkedIn interview question

Given a single-line text string and a maximum width value, write the function 'string justify(string text, int maxWidth)' that formats the input text using full-justification, i.e., extra spaces on each line are equally distributed between the words; the first word on each line is flushed left and the last word on each line is flushed right.

Interview Answers

Anonymous

Dec 5, 2013

public void justify(String input, int lineLength) { String inputNoSpace = input.replace(" ", ""); int actualLength = inputNoSpace.length(); StringTokenizer stk = new StringTokenizer(input); int tknCount = stk.countTokens(); int emptySpace = lineLength - actualLength; if (emptySpace > tknCount) { int space = emptySpace / (tknCount - 1); System.out.println(tknCount); while (stk.hasMoreElements()) { System.out.print(stk.nextElement()); if (emptySpace / (tknCount - 1) > 0) { for (int i = 0; i < space; i++) { System.out.print(" "); emptySpace--; } } if (emptySpace / (tknCount - 1) == 0) { int remainingSpace=emptySpace; for (int j = 0; j < remainingSpace; j++) { System.out.print(" "); emptySpace--; } } } } }

Anonymous

Aug 13, 2014

import java.util.StringTokenizer; public class JustifyText { public static String justify(String s, int len) { if(s.length() == len) return s; if(s.length() > len) { System.out.println("length of string is greater than line-justify length"); return s; } int count = 0; StringTokenizer st = new StringTokenizer(s," "); count = st.countTokens() - 1; int totalSpacing = len - s.length() + count; int individualSpacing = totalSpacing/count; int padding = totalSpacing % count; StringBuilder sb = new StringBuilder(); while(st.hasMoreTokens()) { sb.append(st.nextToken()); if(st.hasMoreTokens()) { for(int i = 0; i 0) { sb.append(" "); --padding; } } return sb.toString(); } public static void main(String[] args) { // TODO Auto-generated method stub String test = "Hello this is a test string"; System.out.println(justify(test,40)); System.out.println(justify(test,32)); } }

1

Anonymous

Jul 31, 2012

Be sure to handle case where the input text is shorter than a single line.