I got this question in an interview. Given a string of words, print it such as each line has at most limit
characters, if a word does not fit on the line, print it on the next line and so on.
This is my implementation:
public static void main(String[] args) {
String s = "Even aside from the rain and wind it hadn't been a happy practice session. Fred and George, who had been spying on the Slytherin team, had seen for themselves the speed of those new Nimbus Two Thousand and Ones. They reported that the Slytherin team was no more than seven greenish blurs, shooting through the air like missiles.";
wordWrapper(s, 11);
}
public static void wordWrapper(String s, int limit) {
// Time complexity: O(n) - n size of s
// Space complexity: O(n) - n number of words in s
int charCount = 0;
int i = 0;
String[] words = s.split(" ");
while (i < words.length) {
if (charCount + words[i].length() > limit) {
System.out.println();
charCount = 0;
}
charCount += words[i].length();
System.out.print(words[i] + " ");
i++;
}
}
I'm trying to reduce the space complexity, and just use pointers instead of split()
, this is what I have so far, I'm thinking of keeping track of the last whitespace and going back to insert a line before that word when the limit is reached, if you run the code the new line is inserted correctly but half of the word would still print before the new line. Please let me know what I'm missing. I also would love to look at better approaches. Thank you!
public static void wordWrapper1(String s, int limit) {
int i = 0;
int lastWhitespaceIdx = -1;
int lineCount = 0;
if (s.length() == 0) {
return;
}
while (i < s.length()) {
if (Character.isWhitespace(s.charAt(i))) {
lastWhitespaceIdx = i;
}
if (lineCount + 1 > limit) {
if (!Character.isWhitespace(s.charAt(i + 1))) {
i = lastWhitespaceIdx + 1;
System.out.println();
lineCount = 0;
continue;
} else {
System.out.println();
lineCount = 0;
}
}
lineCount += 1;
System.out.print(s.charAt(i));
i++;
}
}
wordWrapper1
doesn't work, we cannot review or make the correction for you; we can only review the first version (wordWrapper
). I suggest that you read the What topics can I ask about here?Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead.
\$\endgroup\$