Skip to content

Commit edb79ef

Browse files
authored
Merge pull request codeharborhub#3070 from pallasivasai/68
solution for 68 problem is added
2 parents a8883ba + 564cdf6 commit edb79ef

File tree

1 file changed

+222
-0
lines changed

1 file changed

+222
-0
lines changed
Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
---
2+
id: text-justification
3+
title: Text Justification
4+
sidebar_label: 0068. Text Justification
5+
tags:
6+
- String
7+
- Greedy
8+
description: Solution to Leetcode 68 Text Justification
9+
---
10+
11+
## Problem Description
12+
13+
Given an array of strings `words` and a width `maxWidth`, format the text such that each line has exactly `maxWidth` characters and is fully (left and right) justified.
14+
15+
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 `maxWidth` characters.
16+
17+
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line does not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
18+
19+
For the last line of text, it should be left-justified, and no extra space is inserted between words.
20+
21+
**Note:**
22+
23+
- A word is defined as a character sequence consisting of non-space characters only.
24+
- Each word's length is guaranteed to be greater than 0 and not exceed `maxWidth`.
25+
- The input array `words` contains at least one word.
26+
27+
### Examples
28+
29+
**Example 1:**
30+
31+
```
32+
Input: words = ["This", "is", "an", "example", "of", "text", "justification."], maxWidth = 16
33+
Output:
34+
[
35+
"This is an",
36+
"example of text",
37+
"justification. "
38+
]
39+
```
40+
41+
**Example 2:**
42+
43+
```
44+
Input: words = ["What","must","be","acknowledgment","shall","be"], maxWidth = 16
45+
Output:
46+
[
47+
"What must be",
48+
"acknowledgment ",
49+
"shall be "
50+
]
51+
Explanation: Note that the last line is "shall be " instead of "shall be", because the last line must be left-justified instead of fully-justified.
52+
Note that the second line is also left-justified because it contains only one word.
53+
```
54+
55+
**Example 3:**
56+
57+
```
58+
Input: words = ["Science","is","what","we","understand","well","enough","to","explain","to","a","computer.","Art","is","everything","else","we","do"], maxWidth = 20
59+
Output:
60+
[
61+
"Science is what we",
62+
"understand well",
63+
"enough to explain to",
64+
"a computer. Art is",
65+
"everything else we",
66+
"do "
67+
]
68+
```
69+
70+
### Constraints
71+
72+
- 1 <= words.length <= 300
73+
- 1 <= words[i].length <= 20
74+
- words[i] consists of only English letters and symbols.
75+
- 1 <= maxWidth <= 100
76+
- words[i].length <= maxWidth
77+
78+
### Approach
79+
80+
1. Traverse through the words and group them into lines such that the total length of words in each line does not exceed `maxWidth`.
81+
2. Distribute the extra spaces evenly among the words in each line.
82+
3. For the last line, left-justify the text without adding extra spaces between the words.
83+
84+
### Complexity
85+
86+
- Time complexity: $O(n)$, where n is the number of words.
87+
- Space complexity: $O(n)$, where n is the number of words.
88+
89+
### Solution
90+
91+
#### Code in Different Languages
92+
93+
#### Python
94+
95+
```python
96+
class Solution:
97+
def fullJustify(self, words: list[str], maxWidth: int) -> list[str]:
98+
result, current, num_of_letters = [], [], 0
99+
100+
for word in words:
101+
if num_of_letters + len(word) + len(current) > maxWidth:
102+
for i in range(maxWidth - num_of_letters):
103+
current[i % (len(current) - 1 or 1)] += ' '
104+
result.append(''.join(current))
105+
current, num_of_letters = [], 0
106+
current += [word]
107+
num_of_letters += len(word)
108+
109+
result.append(' '.join(current).ljust(maxWidth))
110+
return result
111+
112+
# Example usage:
113+
words = ["This", "is", "an", "example", "of", "text", "justification."]
114+
maxWidth = 16
115+
solution = Solution()
116+
print(solution.fullJustify(words, maxWidth))
117+
```
118+
119+
#### C++
120+
121+
```cpp
122+
#include <vector>
123+
#include <string>
124+
125+
using namespace std;
126+
127+
class Solution {
128+
public:
129+
vector<string> fullJustify(vector<string>& words, int maxWidth) {
130+
vector<string> result, current;
131+
int num_of_letters = 0;
132+
133+
for (const string& word : words) {
134+
if (num_of_letters + word.size() + current.size() > maxWidth) {
135+
for (int i = 0; i < maxWidth - num_of_letters; ++i) {
136+
current[i % (current.size() - 1 ? current.size() - 1 : 1)] += ' ';
137+
}
138+
string line;
139+
for (const string& w : current) {
140+
line += w;
141+
}
142+
result.push_back(line);
143+
current.clear();
144+
num_of_letters = 0;
145+
}
146+
current.push_back(word);
147+
num_of_letters += word.size();
148+
}
149+
string last_line;
150+
for (const string& word : current) {
151+
if (!last_line.empty()) last_line += ' ';
152+
last_line += word;
153+
}
154+
last_line += string(maxWidth - last_line.size(), ' ');
155+
result.push_back(last_line);
156+
157+
return result;
158+
}
159+
};
160+
161+
// Example usage:
162+
int main() {
163+
Solution solution;
164+
vector<string> words = {"This", "is", "an", "example", "of", "text", "justification."};
165+
int maxWidth = 16;
166+
vector<string> justified_text = solution.fullJustify(words, maxWidth);
167+
for (const string& line : justified_text) {
168+
printf("\"%s\"\n", line.c_str());
169+
}
170+
return 0;
171+
}
172+
```
173+
174+
#### Java
175+
176+
```java
177+
import java.util.ArrayList;
178+
import java.util.List;
179+
180+
class Solution {
181+
public List<String> fullJustify(String[] words, int maxWidth) {
182+
List<String> result = new ArrayList<>();
183+
List<String> current = new ArrayList<>();
184+
int num_of_letters = 0;
185+
186+
for (String word : words) {
187+
if (num_of_letters + word.length() + current.size() > maxWidth) {
188+
for (int i = 0; i < maxWidth - num_of_letters; ++i) {
189+
current.set(i % (current.size() - 1 == 0 ? 1 : current.size() - 1), current.get(i % (current.size() - 1 == 0 ? 1 : current.size() - 1)) + " ");
190+
}
191+
result.add(String.join("", current));
192+
current.clear();
193+
num_of_letters = 0;
194+
}
195+
current.add(word);
196+
num_of_letters += word.length();
197+
}
198+
result.add(String.join(" ", current) + " ".repeat(maxWidth - num_of_letters - (current.size() - 1)));
199+
return result;
200+
}
201+
202+
// Example usage
203+
public static void main(String[] args) {
204+
Solution solution = new Solution();
205+
String[] words = {"This", "is", "an", "example", "of", "text", "justification."};
206+
int maxWidth = 16;
207+
List<String> justified_text = solution.fullJustify(words, maxWidth);
208+
for (String line : justified_text) {
209+
System.out.println("\"" + line + "\"");
210+
}
211+
}
212+
}
213+
```
214+
215+
### Complexity Analysis
216+
217+
- Time Complexity: $O(n)$, where n is the number of words.
218+
- Space Complexity: $O(n)$, where n is the number of words.
219+
220+
### References
221+
222+
- **LeetCode Problem**: Text Justification

0 commit comments

Comments
 (0)