Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit405c1a8

Browse files
committed
text justify
1 parent66b4732 commit405c1a8

File tree

1 file changed

+111
-0
lines changed

1 file changed

+111
-0
lines changed

‎string/FullJustify.java

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
packageAlgorithms.string;
2+
3+
importjava.util.ArrayList;
4+
importjava.util.List;
5+
6+
publicclassFullJustify {
7+
publicstaticvoidmain(String[]strs) {
8+
String[]words = {"Listen","to","many,","speak","to","a","few."};
9+
intL =6;
10+
fullJustify(words,L);
11+
}
12+
13+
// SOLUTION 1: recursion.
14+
publicList<String>fullJustify1(String[]words,intL) {
15+
List<String>ret =newArrayList<String>();
16+
17+
if (words ==null) {
18+
returnret;
19+
}
20+
21+
rec(words,L,0,ret);
22+
returnret;
23+
}
24+
25+
publicstaticvoidrec(String[]words,intL,intindex,List<String>list) {
26+
intlen =words.length;
27+
if (index >=len) {
28+
return;
29+
}
30+
31+
intLenTmp =L;
32+
33+
intend =index;
34+
for (inti =index;i <len &&words[i].length() <=L;i++) {
35+
L -=words[i].length();
36+
37+
// the space follow the word.
38+
L--;
39+
end =i;
40+
}
41+
42+
// 最后一个空格收回
43+
L++;
44+
45+
// Count how many words do we have.
46+
intnum =end -index +1;
47+
48+
intextraSpace =0;
49+
intfirstExtra =0;
50+
51+
// 单词数大于1,才需要分配,否则所有的空格加到最后即可
52+
if (num >1) {
53+
extraSpace =L / (num -1);
54+
// 首单词后多跟的空格
55+
firstExtra =L % (num -1);
56+
}
57+
58+
StringBuildersb =newStringBuilder();
59+
for (inti =index;i <=end;i++) {
60+
sb.append(words[i]);
61+
62+
// The space following every word.
63+
if (i !=end) {
64+
sb.append(' ');
65+
}
66+
67+
// 不是最后一行
68+
if (end !=len -1) {
69+
// The first words.
70+
if (firstExtra >0) {
71+
sb.append(' ');
72+
firstExtra--;
73+
}
74+
75+
// 最后一个单词后面不需要再加空格
76+
if (i ==end) {
77+
break;
78+
}
79+
80+
// 每个单词后的额外空格
81+
intcnt =extraSpace;
82+
while (cnt >0) {
83+
sb.append(' ');
84+
cnt--;
85+
}
86+
}
87+
}
88+
89+
// 最后一行的尾部的空格
90+
inttailLen =LenTmp -sb.length();
91+
while (tailLen >0) {
92+
sb.append(' ');
93+
tailLen--;
94+
}
95+
96+
list.add(sb.toString());
97+
rec(words,LenTmp,end +1,list);
98+
}
99+
100+
// SOLUTION 2: iteration.
101+
publicList<String>fullJustify(String[]words,intL) {
102+
List<String>ret =newArrayList<String>();
103+
104+
if (words ==null) {
105+
returnret;
106+
}
107+
108+
rec(words,L,0,ret);
109+
returnret;
110+
}
111+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp