Skip to content

Commit b209753

Browse files
committed
Add TT4.java
1 parent db295b3 commit b209753

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Miscellaneous/TT4.java

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import java.util.*;
2+
3+
public class TT4 {
4+
5+
public static List<String> split(String exampleText, int limit) {
6+
String[] words = exampleText.split("\\s+");
7+
8+
List<String> result = new ArrayList<>();
9+
int left = 0, currPage = 1, totalPages = countTotalChars(words) / limit + 1;
10+
11+
while (left < words.length) {
12+
StringBuilder sb = new StringBuilder();
13+
int right = findRight(words, left, limit - 8);
14+
15+
while (left <= right) {
16+
sb.append(words[left]).append(" ");
17+
left++;
18+
}
19+
20+
sb.append("(").append(currPage).append("/").append(totalPages).append(")").append(" ")
21+
.append(sb.length() - 1);
22+
result.add(sb.toString());
23+
24+
currPage++;
25+
left = right + 1;
26+
}
27+
28+
return result;
29+
}
30+
31+
private static int findRight(String[] words, int left, int limit) {
32+
int right = left;
33+
int sum = words[right].length();
34+
++right;
35+
36+
while (right < words.length && 1 + sum + words[right].length() <= limit) {
37+
sum += words[right].length() + 1;
38+
++right;
39+
}
40+
41+
return right - 1;
42+
}
43+
44+
private static int countTotalChars(String[] words) {
45+
int count = 0;
46+
47+
for (int i = 0; i < words.length; i++) {
48+
count += words[i].length();
49+
50+
if (i != words.length - 1) {
51+
count += 1;
52+
}
53+
}
54+
55+
return count;
56+
}
57+
58+
public static void main(String[] args) {
59+
String exampleText1 = "Write a function that splits long SMS string"
60+
+ " into smaller pieces. Each piece should be less than or"
61+
+ " equal to 160 characters and contains indices at the end."
62+
+ " Function should not break words into pieces. If word does"
63+
+ " not fit -- it should go to the next SMS.";
64+
65+
List<String> result1 = split(exampleText1, 60);
66+
67+
for (String line : result1) {
68+
System.out.println(line);
69+
}
70+
71+
return;
72+
}
73+
}

0 commit comments

Comments
 (0)