I had a coding interview and this question was given. Given a string of words, break up that string into words and output them on separate lines not to exceed N characters long per line. The sample given to me was "A red sweater." and a line length of 8. The words can't be broken up and you have to fit as many words per line as you can. So, for the given example, "A" & "red" would fit on one line and "sweater." added to that line is over the allowed length of characters, so it would get output on a new line.
I started out by splitting the String into a String []. Then created a method that took in the String [] and the line length. I made some assumptions on the edge cases and then looped through the String [].This is where I got very confused on what could I use to represent a single line and how to add a subarray on a single line. I looked up algorithms that will find all subarrays that get close to a sum, but it appeared that it recycles elements and I can't do that.
This is as far as I got before the time ran out:
import java.util.ArrayList;
import java.util.List;
class Solution {
public static void main(String[] args) {
String sentence = "A red sweater.";
String[] words = sentence.split(" ");
Solution newSol = new Solution();
System.out.println(newSol.convertToLines(words, 8));
}
public List<String> convertToLines(String[] myArr, int bound) {
List<String> result = new ArrayList<String>();
if (myArr.length == 0) {
return result;
}
for (int i = 0; i < myArr.length; i++) {
if (myArr[i].length() > bound) {
System.out.println("One or more words is larger than your boundary");
break;
}
//This is where I got into trouble
//This doesn't account for more than 2 elements
//nor how I would output them on separate lines
if (myArr[i].length() + myArr[i].length() <= bound) {
result.add(myArr[i] + " " + myArr[i + 1]);
} else {
result.add(myArr[i]);
}
}
return result;
}
}
I searched all over for this particular problem and couldn't find it. I assume that there is a pattern or something I am missing, but after hours messing with it, I'm still at a loss as where to go from here. I have never coded something similar to this. While it's too late for the interview, I would still like to know how this could be solved so that I can learn from it and keep on learning.