Problem · String
Crop Text at a Whole-Word Boundary
Learn this problemProblem statement
You are given a nonempty string text containing nonempty words separated by single spaces, and a nonnegative integer maxCharacters.
Return the longest prefix of text that:
- has length at most
maxCharacters, - contains only complete words from the beginning of
text, and - does not end with a space.
If the first word does not fit, return the empty string.
Function
cropWords(text: String, maxCharacters: int) → StringExamples
Example 1
text = "The quick brown fox"maxCharacters = 10return = "The quick"Adding the next word would make the prefix longer than 10 characters, so the result ends after quick.
Example 2
text = "hello world"maxCharacters = 4return = ""The first word has five characters, so no complete word fits.
Example 3
text = "one two"maxCharacters = 7return = "one two"The entire text has exactly seven characters.
Constraints
1 <= text.length <= 2000000 <= maxCharacters <= 1000000textcontains printable non-space characters grouped into words separated by exactly one space.