
You are given a long string of text and a maximum character length for a tweet. Your task is to write a function that splits the text into one or more tweets.
The splitting must adhere to the following rules:
Your function should return a list or array of the resulting tweet strings.
The first line of input contains the string text.
The second line of input contains an integer maxLength.
Print the resulting tweet strings, one per line.
If the text is empty or contains only spaces, print nothing.
If any single word in the text is too long to fit in a tweet even by itself (after accounting for the suffix), the task is impossible. In this case, print a single line with the string Error: Word too long.
The core challenge is that you don't know the total number of tweets (T in (i/T)) until you've already split the text. But the length of T (e.g., whether it's a 1-digit or 2-digit number) affects the available space in each tweet, which in turn affects the splitting.
The optimal solution involves an iterative approach: first, try to split the text assuming there will be 1 total tweet. If that fails, try to split it assuming there will be 2 total tweets, and so on, until a valid split is found. The first valid split will be the one with the minimum possible number of tweets.
This is a very long text that needs to be split into several parts because it exceeds the character limit.
50
This is a very long text that needs to be (1/3)
split into several parts because it exceeds (2/3)
the character limit. (3/3)
The function determines that the text must be split into 3 tweets. It calculates the space needed for the suffix `(x/3)` (which is 4 characters) and then greedily fits words into each tweet.
- Tweet 1: `45 chars of text + 1 space + 4 char suffix = 50`.
- Tweet 2: `42 chars of text + 1 space + 4 char suffix = 47`.
- Tweet 3: `22 chars of text + 1 space + 4 char suffix = 27`.
All are ≤ 50 characters.
antidisestablishmentarianism is a long word
25
Error: Word too long
The word "antidisestablishmentarianism" has 28 characters. This is longer than the `maxLength` of 25, so it's impossible to create a valid tweet.
The expected time complexity is O(N^2), where N is the number of words in the string.
1 <= N (length of text) <= 5000
10 <= maxLength <= 280
Time limit: 1 sec
The expected time complexity is O(N^2), where N is the number of words in the string.