Text Justification

Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.

You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces' ' when necessary so that each line has exactly L characters.

Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.

For the last line of text, it should be left justified and no extra space is inserted between words.

For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.

Return the formatted lines as:

[
   "This    is    an",
   "example  of text",
   "justification.  "
]

 

Note: Each word is guaranteed not to exceed L in length.

C++:
01 vector<string> fullJustify(vector<string> &words, int L) {
02         vector<string> result;
03         int n=words.size();
04         for(int i=0;i<n; ){
05             string tmp;
06             int cnt=0;
07             int start=i;
08             cnt+=words[i++].size();
09             while((i<n)&&(cnt+words[i].size()+1<=L))
10                 cnt+=words[i++].size()+1;
11             if(start==i1){
12                 tmp+=words[start];
13                 for(int j=cnt;j<L;j++)
14                     tmp+=‘ ‘;
15                 result.push_back(tmp);
16                 continue;
17             }
18             if(i<n){
19                 int t=(Lcnt)/(istart1);
20                 int r=(Lcnt)%(istart1);
21                 for(int j=start;j<i1;j++){
22                     tmp+=words[j];
23                     for(int m=0;m<=t;m++)
24                         tmp+=‘ ‘;
25                     if(r>0){
26                         tmp+=‘ ‘;
27                         r;
28                     }
29                 }
30                 tmp+=words[i1];
31                 result.push_back(tmp);
32             }
33             else{
34                 for(int j=start;j<i1;j++){
35                         tmp+=words[j];
36                         tmp+=‘ ‘;
37                     }
38                 tmp+=words[i1];
39                 for(int j=cnt;j<L;j++)
40                       tmp+=‘ ‘;
41                 result.push_back(tmp);
42             }
43         }
44         return result;
45 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s