MCPcopy Create free account
hub / github.com/Hsinha11/Leetcode-solutions / fullJustify

Method fullJustify

-68-Text_Justification/Code.cpp:11–54  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

9 }
10
11 vector<string> fullJustify(vector<string>& words, int maxWidth) {
12 vector<string> ans;
13 int ind = 0;
14 int n = words.size();
15
16 while (ind < n) {
17 int charsLength = words[ind].length();
18 int last = ind + 1;
19
20 while (last < n) {
21 if (charsLength + 1 + words[last].length() > maxWidth)
22 break;
23 charsLength += 1 + words[last].length();
24 last++;
25 }
26
27 int diff = last - ind - 1;
28 string str = "";
29
30 if (diff == 0 || last == n) {
31 for (int i = ind; i < last; i++) {
32 str += words[i];
33 if (i < last - 1) str.push_back(' ');
34 }
35 int countSpaces = maxWidth - str.length();
36 addSpaces(str, countSpaces);
37 } else {
38 int spaces = (maxWidth - charsLength) / diff;
39 int remSpaces = (maxWidth - charsLength) % diff;
40 for (int i = ind; i < last; i++) {
41 str += words[i];
42 if (i < last - 1) {
43 int countSpaces = spaces + (i - ind < remSpaces ? 1 : 0);
44 addSpaces(str, 1 + countSpaces);
45 }
46 }
47 }
48
49 ans.push_back(str);
50 ind = last;
51 }
52
53 return ans;
54 }
55};
56
57int main() {

Callers 1

mainFunction · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected