2129. Capitalize the Title

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
class Solution {
public String capitalizeTitle(String title) {
StringBuilder sb = new StringBuilder(title.length());
for (String word : title.split(" ", -1)) {
if (sb.length() > 0) {
sb.append(" ");
}
sb.append(capitalize(word));
}
return sb.toString();
}

private String capitalize(String word) {
if (word.length() <= 2) {
return word.toLowerCase();
} else {
char[] chars = word.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
for (int i = 1; i < chars.length; i++) {
chars[i] = Character.toLowerCase(chars[i]);
}
return new String(chars);
}
}
}

References

2129. Capitalize the Title