forked from srinathr91/TestJava
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordsLenLast.java
More file actions
134 lines (112 loc) · 3.74 KB
/
WordsLenLast.java
File metadata and controls
134 lines (112 loc) · 3.74 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package com.String;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class WordsLenLast {
public ArrayList<String> fullJustify(ArrayList<String> words, int L) {
ArrayList<String> res = new ArrayList<String>();
if(words.size() == 0 || L == 0){
res.add("");
return res;
}
if(words.size() == 1 && words.get(0).length() == 0){
res.add(generateSpaces(L));
return res;
}
int index = 0;
while(index < words.size()){
if(words.get(index).length()>L){
res.clear();
break;
}
//Need to take care of the cases when words contains any number of ""(empty string).
if(words.get(index).length() == 0){
index++;
continue;
}
int cur = index+1;
int len = words.get(index).length();
String curLine = words.get(index);
while(cur<words.size()){
int temp = len + words.get(cur).length() + 1;
if(temp<=L){
curLine += " "+words.get(cur);
len = temp;
index = cur;
cur ++;
}
else{
index = cur-1;
break;
}
}
index++;
if(index == words.size()){
curLine = justifyString(curLine,L,true);
}
else curLine = justifyString(curLine,L,false);
res.add(curLine);
}
return res;
}
public String justifyString(String s,int L, boolean isLastLine){
String reg = "\\s+";
String[] last = s.split(reg);
if(!isLastLine){
int len = 0;
for(String str : last)
len += str.length();
int space = L-len;
int slots = last.length-1;
int remain = 0;
int even = space;
if(slots!=0){
remain = space % slots;
even = space / slots;
}
StringBuilder refined = new StringBuilder();
for(String str : last){
if(space>0){
str += generateSpaces(even);
space -= even;
if(remain>0){
str += " ";
remain--;
space--;
}
}
refined.append(str);
}
return refined.toString();
}
else{
StringBuilder refineLast = new StringBuilder();
refineLast.append(last[0]);
for(int i=1;i<last.length;i++){
refineLast.append(" ");
refineLast.append(last[i]);
}
String res = refineLast.toString();
int space = L-res.length();
res += generateSpaces(space);
return res;
}
}
public String generateSpaces(int length){
if(length<1)
return "";
StringBuilder res = new StringBuilder();
while(length>0){
res.append(" ");
length--;
}
return res.toString();
}
public static void main(String[] args) {
Random rr=new Random();
int a=rr.nextInt(10);
System.out.println(a);
}
}