PROBLEM STATEMENT:
You are given a String of text which must be printed onto a screen of a given
width. The width represents the number of characters (including spaces) that
can fit on a single line. The text contains only letters and spaces. Arrange
the text using these rules:
- In each line of text, there should be a single space between each word (so if
the original text contains words separated by multiple spaces, those spaces
should be compressed to a single space).
- No line should ever begin with a space (so if the original text contains
spaces before the first word, remove them)
- Fit as many words as possible onto each line without exceeding the width.
Each word must exist completely on a single line (a single word cannot be
broken up to occupy multiple lines). Words must not be displayed out of their
original order in the text.
Now, for each non-empty line (non-empty = contains at least one word),
calculate the number of spaces that occur between the last letter of the line
and the right edge of the screen. Return the total sum of these values.
DEFINITION
Class name: RightMargin
Method name: getTotal
Parameters: String, int
Returns: int
The method signature is:
public int getTotal(String text, int width);
Make sure your method is public.
TopCoder will ensure the validity of the inputs. Inputs are valid if all of
the following criteria are met:
- text can only contain letters (A-Z, a-z) and spaces.
- text will contain between 0 and 50 characters inclusive.
- width will be between 1 and 50 inclusive.
- No word in the original text will be longer than the width.
NOTES
- The screen can display an unlimited number of lines
EXAMPLES:
---------
Example 1
---------
text - "this is a test"
width - 5
The text will be arranged in the following manner (in all these examples, the
first row shows the width of the screen and is only there for reference):
12345
this
is a
test
Each line contains one space between the last character and the right edge of
the screen. So, the total is 3.
---------
Example 2
---------
text - "No extra spaces allowed"
width - 9
123456789
No extra
spaces
allowed
The first line contains one space between the last character and right edge,
the second line contains three, and the third contains two.
Return value: 6
---------
Example 3
---------
text - " TopCoder TopCoder "
width - 8
12345678
TopCoder
TopCoder
The two words each take up the entire width of a line, so there is no space
left over.
Return value: 0
---------
Example 4
---------
text - " "
width - 3
123
There are no words to display, so there are no non-empty lines. Therefore,
there is no space left over.
Return value: 0
---------
Example 5
---------
text - " take me down to the paradise city "
width - 8
12345678
take me
down to
the
paradise
city
Return value: 11