Given a string s and an integer k, break up the string into multiple lines such that each line has a length of k or less. You must break it up so that words don’t break across lines. Each line has to have the maximum possible amount of words. If there’s no way to break the text up, then return null.
You can assume that there are no spaces at the ends of the string and that there is exactly one space between each word.
Input: s ="the quick brown fox jumps over the lazy dog", k =10Output: ["the quick","brown fox","jumps over","the lazy","dog"]Explanation: Each line has a length of 10 or less with maximum words per line and no words are split across lines.
classSolution:
defbreakString(self, s: str, k: int) -> Optional[List[str]]:
words = s.split(" ")
result = []
current_line =""for word in words:
if len(word) > k:
returnNone# If any word is longer than k, return Noneif len(current_line) + len(word) + (1if current_line else0) > k:
result.append(current_line)
current_line =""if current_line:
current_line +=" " current_line += word
if current_line:
result.append(current_line)
return result
# For testing the solutionif __name__ =="__main__":
solution = Solution()
print(solution.breakString("the quick brown fox jumps over the lazy dog", 10))
# Output: ["the quick", "brown fox", "jumps over", "the lazy", "dog"] print(solution.breakString("hello world", 5)) # Output: None