[InterviewBit] Justified Text

Justified Text

  • Time : O(A)
  • Space : O(1)
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
vector<string> Solution::fullJustify(vector<string> &A, int B) {
int l = 0, n = A.size();
vector<string> res;
while(l < n) {
int now = A[l].length();
int space = 0;
int r = l + 1;
while(r < n and now + space + 1 + A[r].length() <= B) {
now += A[r++].length();
space += 1;
}
space = B - now;
int eqspace = r-l-1 ? space / (r-l-1) : 0;
int gap = B - now - eqspace * (r-l-1);
string s = "";
if(r != n) {
while(l < r) {
s += A[l++] + string(eqspace, ' ');
if(gap) {
s.push_back(' ');
gap--;
}
}
} else while(l < r) s += A[l++] + " ";
while(s.length() < B) s.push_back(' ');
while(s.length() > B) s.pop_back();
res.push_back(s);
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/31/PS/interviewbit/justified-text/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.