-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
69 lines (69 loc) · 1.82 KB
/
solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class Solution
{
public:
vector<string> fullJustify(vector<string> &words, int L)
{
int start = 0;
int size = words.size();
int len = words[0].size();
vector<string> ans;
for(int i = 1 ; i < size ; ++i)
{
if(len + words[i].size() + 1 > L)
{
string result = addSpace(words, start , i , len , L);
ans.push_back(result);
start = i;
len = words[i].size();
}
else
{
len += words[i].size() + 1;
}
}
//procee last
string result = addLast(words, start , size , L);
ans.push_back(result);
return ans;
}
private:
//[start,end)
string addSpace(vector<string>& words , int start , int end , int len , int L)
{
int exspace = L - len;
int cnt = end - start;
string tmp = "";
if(cnt == 1)
{
tmp = words[start];
tmp.append(exspace , ' ');
}
else
{
int avespace = exspace / (cnt - 1);
int reminder = exspace % (cnt - 1);
for(int i = start ; i < end - 1 ; ++i)
{
tmp += words[i];
tmp.append(avespace + 1 , ' ');
if(reminder)
{
tmp.append(1 , ' ');
reminder --;
}
}
tmp += words[end-1];
}
return tmp;
}
string addLast(vector<string>& words , int start , int end , int L)
{
string tmp = words[start];
for(int i = start + 1 ; i < end ; ++i)
{
tmp += " " + words[i];
}
if(tmp.size() < L) tmp.append(L - tmp.size() , ' ');
return tmp;
}
};