68. Text Justification
Tags:
Hard
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Problem
Approach
Time and space complexity
Solution
1function fullJustify(words: string[], maxWidth: number): string[] {
2 const res: string[] = [];
3 let i = 0;
4 const n = words.length;
5
6 while (i < n) {
7 let line_words: string[] = [words[i]];
8 let line_length = words[i].length;
9 i++;
10
11 while (i < n && line_length + 1 + words[i].length <= maxWidth) {
12 line_words.push(words[i]);
13 line_length += 1 + words[i].length;
14 i++
15 }
16
17 if (i === n || line_words.length === 1) {
18 const line = line_words.join(" ");
19 res.push(line + ' '.repeat(maxWidth - line.length));
20 continue;
21 }
22
23 const total_spaces = maxWidth - (line_length - (line_words.length - 1));
24 const space_per_gap = Math.floor(total_spaces / (line_words.length - 1));
25 const extra_spaces = total_spaces % (line_words.length - 1);
26
27 let line = '';
28 for (let j = 0; j < line_words.length - 1; j++) {
29 line += line_words[j];
30 line += ' '.repeat(space_per_gap + (j < extra_spaces ? 1 : 0));
31 }
32 line += line_words[line_words.length - 1];
33 res.push(line);
34 }
35
36 return res;
37};space_per_gap là gì?maxWidth space_per_gap = Math.floor(total_spaces / (line_words.length - 1))
extra_spaces ?total_spaces ) cho số khoảng trống giữa các từ (line_words.length - 1 ), thường sẽ dư ra một số khoảng trắng (không chia hết)extra_spaces chính là phần dư này:extra_spaces = total_spaces % (line_words.length - 1)
line_len đã bao gồm cả dấu cách tối thiểu giữa các từ (mỗi từ thêm sau sẽ cộng thêm 1 dấu cách)line_len ), để chỉ còn tổng độ dài các ký tự của các từline_len - (line_words.length - 1) = tổng số ký tự của các từ (không tính dấu cách)maxWidth - (line_len - (line_words.length - 1)) = tổng số khoảng trắng cần chèn vào dòng để đủ độ dài maxWidthCụ thể: