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

Class Main

-68-Text_Justification/Code.java:3–73  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1import java.util.*;
2
3public class Main {
4 static class Solution {
5 void addSpaces(StringBuilder str, int count) {
6 for (int i = 0; i < count; i++)
7 str.append(' ');
8 }
9
10 public List<String> fullJustify(String[] words, int maxWidth) {
11 List<String> ans = new ArrayList<>();
12 int ind = 0, n = words.length;
13
14 while (ind < n) {
15 int charsLength = words[ind].length();
16 int last = ind + 1;
17
18 while (last < n) {
19 if (charsLength + 1 + words[last].length() > maxWidth)
20 break;
21 charsLength += 1 + words[last].length();
22 last++;
23 }
24
25 int diff = last - ind - 1;
26 StringBuilder str = new StringBuilder();
27
28 if (diff == 0 || last == n) {
29 for (int i = ind; i < last; i++) {
30 str.append(words[i]);
31 if (i < last - 1) str.append(' ');
32 }
33 addSpaces(str, maxWidth - str.length());
34 } else {
35 int spaces = (maxWidth - charsLength) / diff;
36 int remSpaces = (maxWidth - charsLength) % diff;
37 for (int i = ind; i < last; i++) {
38 str.append(words[i]);
39 if (i < last - 1) {
40 int countSpaces = spaces + (i - ind < remSpaces ? 1 : 0);
41 addSpaces(str, 1 + countSpaces);
42 }
43 }
44 }
45
46 ans.add(str.toString());
47 ind = last;
48 }
49
50 return ans;
51 }
52 }
53
54 public static void main(String[] args) {
55 Scanner sc = new Scanner(System.in);
56 System.out.print("Enter number of words: ");
57 int n = sc.nextInt();
58 String[] words = new String[n];
59 System.out.println("Enter words:");
60 for (int i = 0; i < n; i++)

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected